public MatrixItem getNextLocation(Directions direction) { MatrixItem result = null; switch (direction) { case Directions.Right: result = location.East; break; case Directions.Left: result = location.West; break; case Directions.Up: result = location.North; break; case Directions.Down: result = location.South; break; default: throw new Exception("No correct direction"); } return(result); }
public static ImplicitMatrix <T> operator *(ImplicitMatrix <T> m1, ImplicitMatrix <T> m2) { if (m1.Columns != m2.Rows) { throw new Exception("Matrix multiplication error, row of m1 isn't equal to the column count of m2"); } ImplicitMatrix <T> output = new ImplicitMatrix <T>(m1.Rows, m2.Columns); for (int i = 0; i < output.Rows; i++) { for (int j = 0; j < output.Columns; j++) { CalculatingUnit <T> item = bop.Zero(); foreach (MatrixItem mItem1 in m1.mRf[i]) { if (m2.mCf[j].Exists(x => x.row == mItem1.column)) { MatrixItem mItem2 = m2.mCf[j].Find(x => x.row == mItem1.column); item = bop.Add(item, bop.Multiply(mItem1.value, mItem2.value)); } } output[i, j] = item; } } return(output); }
public ConfusionMatrixAnalysis CreateConfusionMatrix(List <TestResultModel[]> foldResults) { var confusionMatrix = new ConfusionMatrixAnalysis(this._applicationVersion); foreach (var testResults in foldResults) { foreach (var utterance in testResults.Where(x => !x.IsCorrect)) { var confusionModel = confusionMatrix.MatrixItems.FirstOrDefault(x => x.ExpectedIntentName == utterance.IntentLabel); if (confusionModel == null) { confusionModel = new MatrixItem(confusionMatrix, utterance.IntentLabel); confusionMatrix.MatrixItems.Add(confusionModel); } var confusion = confusionModel.Confusions.FirstOrDefault(x => x.FoundIntent == utterance.FirstIntent.Name); if (confusion == null) { confusion = new Confusion(confusionModel, utterance.FirstIntent.Name); confusionModel.Confusions.Add(confusion); } var predictions = utterance.IntentPredictions.OrderByDescending(x => x.Score).Take(10).Select(x => new UtteranceIntents(x.Name, x.Score)).ToList(); confusion.Utterances.Add(new Utterance(confusion, utterance.Text, utterance.TokenizedText, utterance.FirstIntent.Score, predictions)); } } return(confusionMatrix); }
public void AddRow(MatrixItem[] Row) { if (Width == Row.Length) { MatrixItem LastItem = null; MatrixItem SouthWestCorner = GetSouthWestCornerItem(); foreach (MatrixItem item in Row) { if (item.occupant is Player) { player = (Player)item.occupant; } if (LastItem == null) { // Set up the first item of the row. SouthWestCorner.South = item; item.North = SouthWestCorner; } else { // Connect the rest of the items to the Matrix. var Above = LastItem.North.East; LastItem.East = item; item.West = LastItem; Above.South = item; item.North = Above; } LastItem = item; } } }
/// <summary> /// Creates a new edit distance matrix, and initializes the border elements. /// </summary> private MatrixItem[,] CreateEditDistanceMatrix(IList <Core.Tokenization.Token> sourceTokens, IList <Core.Tokenization.Token> targetTokens) { MatrixItem[,] matrix = new MatrixItem[sourceTokens.Count + 1, targetTokens.Count + 1]; int i; int j; matrix[0, 0] = new MatrixItem(0.0d, EditOperation.Identity, 0.0d); for (i = 1; i <= sourceTokens.Count; ++i) { matrix[i, 0] = new MatrixItem((double)i * _InsertDeleteCosts, EditOperation.Delete, 0.0d); } for (j = 1; j <= targetTokens.Count; ++j) { matrix[0, j] = new MatrixItem((double)j * _InsertDeleteCosts, EditOperation.Insert, 0.0d); } for (i = 1; i <= sourceTokens.Count; ++i) { for (j = 1; j <= targetTokens.Count; ++j) { matrix[i, j] = new MatrixItem(0.0d, EditOperation.Undefined, 0.0d); } } return(matrix); }
public T this[int row, int column] { get { if (mRf[row].Exists(x => x.column == column)) { return(mRf[row].Find(x => x.column == column).value); } else { return(bop.Zero()); } } set { mRf[row].RemoveAll(x => x.column == column); mCf[column].RemoveAll(x => x.row == row); if (bop.CompareTo(value, bop.Zero()) != 0) { MatrixItem item = new MatrixItem() { column = column, row = row, value = value }; mRf[row].Add(item); mCf[column].Add(item); } } }
public static MyListData GetSchedule() { MyListData objTab = new MyListData(); objTab.HeaderItems = new List <HeaderItem>(); //Header loop works perfectly for (int x = 0; x < 7; x++) { HeaderItem objItem = new HeaderItem(); objItem.strHeadName = x; objTab.HeaderItems.Add(objItem); } objTab.MatrixItems = new List <MatrixItem>(); for (int x = 0; x < 7; x++) { MatrixItem objItem = new MatrixItem(); objItem.nHRJobID = x; objTab.MatrixItems.Add(objItem); } //Only adds the last one Need ALL return(objTab); }
private void CreateGamestate() { player = new Player(); box1 = new Box(); box2 = new Box(); hok1 = new MatrixItem(); hok2 = new MatrixItem(); hok3 = new MatrixItem(); }
public MatrixItem GetSouthWestCornerItem() { MatrixItem current = Origin; while (current.South != null) { current = current.South; } return(current); }
public void setRattingMatrix(MatrixItem matrixItem) { Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("@ClusterID", matrixItem.ClusterID); parameters.Add("@UserID", matrixItem.Row); parameters.Add("@MetaItemID", matrixItem.Column); parameters.Add("@Value", matrixItem.Cell); executeNonQuery("INSERT INTO [RS].[RATING_MATRIX] ([ClusterID] ,[UserID] ,[MetaItemID] ,[Value]) VALUES (@ClusterID ,@UserID ,@MetaItemID ,@Value)", parameters); }
private static MatrixItem[] MatrixItemsFromString(String BoardItemRow) { MatrixItem[] Row = new MatrixItem[BoardItemRow.Length]; var chars = BoardItemRow.ToCharArray(); for (int i = 0; i < chars.Length; i++) { Row[i] = MatrixItemFactory.Create(chars[i]); } return(Row); }
public static List <Tuple <HeaderItem, MatrixItem> > GetScheduleCombined() { List <Tuple <HeaderItem, MatrixItem> > list = new List <Tuple <HeaderItem, MatrixItem> >(); for (int x = 0; x < 7; x++) { var h = new HeaderItem(); h.strHeadName = x; var m = new MatrixItem(); m.nHRJobID = x; list.Add(new Tuple <HeaderItem, MatrixItem>(h, m)); } return(list); }
public List <MatrixItem> computeRattingMatrixItem(string U_SubCategoryID, double Alpha) { string strSelect = "SELECT x1.UserID, x2.MetaItemID, (@Alpha1*(x2.S1*1.0/x1.SU + x2.S1*1.0/x3.SG) + @Alpha2*(x2.F1*1.0/x1.FU + x2.F1*1.0/x3.FG))/2.0 As Rate FROM " + "(SELECT [RS].[USER_TBL].UserID, SUM([Quantity]) as SU, count(*) as FU FROM [RS].[TRANSACTION_TBL], [RS].[USER_TBL] " + "WHERE [RS].[TRANSACTION_TBL].[UserID] = [RS].[USER_TBL].[UserID] and [RS].[USER_TBL].U_SubCategoryID = @U_SubCategoryID " + "GROUP BY [RS].[USER_TBL].UserID) X1, " + "(SELECT [RS].[USER_TBL].UserID, [RS].[ITEM_TBL].[MetaItemID], SUM([Quantity]) as S1, count(*) as F1 FROM [RS].[TRANSACTION_TBL], [RS].[ITEM_TBL], [RS].[USER_TBL] " + "WHERE [RS].[TRANSACTION_TBL].[UserID] = [RS].[USER_TBL].[UserID] and [RS].[TRANSACTION_TBL].ItemID = [RS].ITEM_TBL.ItemID and [RS].[USER_TBL].U_SubCategoryID = @U_SubCategoryID " + "GROUP BY [RS].[USER_TBL].UserID, [RS].[ITEM_TBL].[MetaItemID]) X2, " + "(SELECT [RS].[ITEM_TBL].[MetaItemID], SUM([Quantity]) as SG, count(*) as FG FROM [RS].[TRANSACTION_TBL], [RS].[ITEM_TBL], [RS].[USER_TBL] " + "WHERE [RS].[TRANSACTION_TBL].[UserID] = [RS].[USER_TBL].[UserID] and [RS].[TRANSACTION_TBL].ItemID = [RS].ITEM_TBL.ItemID and [RS].[USER_TBL].U_SubCategoryID = @U_SubCategoryID " + "GROUP BY [RS].[ITEM_TBL].[MetaItemID]) X3 " + "WHERE X1.UserID = X2.UserID AND X2.MetaItemID = X3.MetaItemID and (@Alpha1*(x2.S1*1.0/x1.SU + x2.S1*1.0/x3.SG) + @Alpha2*(x2.F1*1.0/x1.FU + x2.F1*1.0/x3.FG))/2.0 >0"; //string strSelect = "SELECT x2.[UserID], x2.MetaItemID, ((x2.QTY*1.0/x1.M*1.0) + (x2.FRE*1.0/x1.N*1.0))/2.0 as 'Rate' FROM (SELECT MAX([Quantity]) as M ,count(*) as N ,[RS].[USER_TBL].U_SubCategoryID ,[MetaItemID] FROM [RS].[TRANSACTION_TBL], [RS].[USER_TBL], [RS].ITEM_TBL WHERE [RS].[TRANSACTION_TBL].[UserID] = [RS].[USER_TBL].[UserID] and [RS].[TRANSACTION_TBL].ItemID = [RS].ITEM_TBL.ItemID and [RS].[USER_TBL].U_SubCategoryID = @U_SubCategoryID GROUP BY [MetaItemID], [RS].[USER_TBL].U_SubCategoryID ) x1 inner join (SELECT [RS].[TRANSACTION_TBL].[UserID] ,[MetaItemID] ,SUM([Quantity]) as QTY ,count(*) as FRE , [RS].[USER_TBL].U_SubCategoryID FROM [RS].[TRANSACTION_TBL], [RS].[USER_TBL], [RS].ITEM_TBL WHERE [RS].[TRANSACTION_TBL].[UserID] = [RS].[USER_TBL].[UserID] and [RS].[TRANSACTION_TBL].ItemID = [RS].ITEM_TBL.ItemID and [RS].[USER_TBL].U_SubCategoryID = @U_SubCategoryID GROUP BY [RS].[TRANSACTION_TBL].[UserID], [MetaItemID], [RS].[USER_TBL].U_SubCategoryID ) x2 on (x1.U_SubCategoryID = x2.U_SubCategoryID and x1.[MetaItemID] = x2.[MetaItemID]) WHERE ((x2.QTY*1.0/x1.M*1.0) + (x2.FRE*1.0/x1.N*1.0))/2.0 > 0 "; Dictionary <string, object> parameters = new Dictionary <string, object>(); string str1 = Alpha.ToString(CultureInfo.CreateSpecificCulture("en-GB")); string str2 = (1 - Alpha).ToString(CultureInfo.CreateSpecificCulture("en-GB")); parameters.Add("@Alpha1", str1); parameters.Add("@Alpha2", str2); parameters.Add("@U_SubCategoryID", U_SubCategoryID); SqlDataReader dr = executeReader(strSelect, parameters); List <MatrixItem> list = new List <MatrixItem>(); while (dr.Read()) { double rate = 0; try { rate = (dr[1] == System.DBNull.Value) ? 0.0 : Convert.ToDouble(dr[2].ToString()); } catch (Exception ex) { throw ex; } MatrixItem obj = new MatrixItem(); obj.Row = dr.GetString(dr.GetOrdinal("UserID")); obj.Column = dr.GetString(dr.GetOrdinal("MetaItemID")); obj.Cell = rate; list.Add(obj); } dr.Close(); return(list); }
public static MatrixItem Create(Char input) { var item = MatrixItemFromChar(input); var MatrixItem = new MatrixItem() { occupant = item }; if (item != null) { item.location = MatrixItem; } else if (input == 'x') { MatrixItem.IsDestination = true; } return(MatrixItem); }
public void Move(Directions direction) { if (!canMove(direction)) { return; } MatrixItem nextLocation = getNextLocation(direction); if (nextLocation.occupant is isMovable) { isMovable nextItem = (isMovable)nextLocation.occupant; nextItem.Move(direction); } location.occupant = null; location = nextLocation; location.occupant = this; }
public IncomeMatrixItem(DataRow newdrow) { id = Convert.ToInt32(newdrow["ID"]); grpid = Convert.ToInt32(newdrow["IncomeGroup"]); catLabel1 = newdrow["Label1"].ToString(); catLabel2 = newdrow["Label2"].ToString(); catLabel3 = newdrow["Label3"].ToString(); created = Convert.ToDateTime(newdrow["Created"]); createdby = newdrow["CreatedBy"].ToString(); modified = Convert.ToDateTime(newdrow["Modified"]); modifiedby = newdrow["ModifiedBy"].ToString(); for (int i = 1; i < 11; i++) { MatrixItem mItm = new MatrixItem(); mItm.IncomeLow = Convert.ToInt32(newdrow["IncomeLow" + i.ToString()]); mItm.IncomeHi = Convert.ToInt32(newdrow["IncomeHi" + i.ToString()]); incomeRange.Add(mItm); } }
public DoublyLinkedMatrix(MatrixItem[] FirstRow) { Width = FirstRow.Length; MatrixItem LastItem = null; foreach (MatrixItem item in FirstRow) { if (Origin == null) { Origin = item; } else { LastItem.East = item; item.West = LastItem; } LastItem = item; } End = LastItem; }
public void Move(Directions direction) { MatrixItem nextLocation = getNextLocation(direction); /*Eerst het huidige hoke leegmaken * daarna this in het nextitem stoppen * daarna location veranderen naar nextitem */ location.occupant = null; location = nextLocation; location.occupant = this; if (location.IsDestination) { this.view = '0'; } else { view = 'O'; } }
private MatrixItem[] getDestinations(DoublyLinkedMatrix matrix) { List <MatrixItem> destinations = new List <MatrixItem>(); MatrixItem currentElement = matrix.Origin; while (currentElement.South != null) { var innerCurrentElement = currentElement; do { if (innerCurrentElement.IsDestination) { destinations.Add(innerCurrentElement); } innerCurrentElement = innerCurrentElement.East; }while (innerCurrentElement.East != null); // Move one line lower currentElement = currentElement.South; } return(destinations.ToArray()); }
public void Move(Directions direc) { // int move = random.Next(1,4); int move = 1; Directions direction = Directions.Right; switch (move) { case 1: direction = Directions.Left; break; case 2: direction = Directions.Right; break; case 3: direction = Directions.Up; break; case 4: direction = Directions.Down; break; } MatrixItem nextLocation = getNextLocation(direction); if (!(nextLocation.occupant is isMovable && nextLocation.occupant != null)) { return; } else if (nextLocation.occupant is isMovable) { isMovable nextItem = (isMovable)nextLocation.occupant; nextItem.Move(direction); } location.occupant = null; location = nextLocation; location.occupant = this; }
private void calculateMatrix() { var tl = new Point(_minPoint.X - _sideAreaOffset, _minPoint.Y - _sideAreaOffset); var br = new Point(_maxPoint.X + _sideAreaOffset, _maxPoint.Y + _sideAreaOffset); var hCount = (int)((br.X - tl.X) / _horizontalGS) + 1; var vCount = (int)((br.Y - tl.Y) / _verticalGS) + 1; resMatrix = new MatrixItem[hCount, vCount]; validPoints = new List <MatrixItem>(); var lastPt = new Point(0, 0); //get the intersection matrix for (int i = 0; i < hCount; i++) { for (int j = 0; j < vCount; j++) { lastPt = new Point(tl.X + _horizontalGS * i, tl.Y + _verticalGS * j); resMatrix[i, j] = new MatrixItem(lastPt, IsOverlapped(lastPt), i, j); if (!resMatrix[i, j].IsIntersected) { validPoints.Add(resMatrix[i, j]); } } } ////////////debug for (int i = 0; i < vCount; i++) { var str = ""; for (int j = 0; j < hCount; j++) { str += resMatrix[j, i].IsIntersected ? "0 " : "1 "; } Debug.WriteLine(str); } ///////// }
public void Render() { System.Console.Clear(); _board = _game.Board; MatrixItem leftHelper = _board.Origin; MatrixItem currentElement = leftHelper; string line; while (currentElement != null) { line = ""; do { if (currentElement.occupant == null) { if (currentElement.IsDestination) { line += 'x'; } else { line += "."; } } else { line += currentElement.occupant.view; } currentElement = currentElement.East; }while (currentElement != null); leftHelper = leftHelper.South; currentElement = leftHelper; Console.WriteLine(line); } Console.WriteLine(""); Console.WriteLine("Laat met de pijltjestoetsen de speler bewegen."); }
private EditDistance ComputeEditDistance(double[,] sim, PositionRange srcRange, PositionRange trgRange) { const double invalidAssignmentCosts = 100000.0d; // TODO handle special cases (one/both of the arrays being empty/having no elements) // TODO use diagonal algorithm int i; int j; int sourceObjectsCount = srcRange.Into - srcRange.Start + 1; int targetObjectsCount = trgRange.Into - trgRange.Start + 1; EditDistance result = new EditDistance(sourceObjectsCount, targetObjectsCount, 0.0d); MatrixItem[,] matrix = new MatrixItem[sourceObjectsCount + 1, targetObjectsCount + 1]; // initialize matrix matrix[0, 0] = new MatrixItem(0.0d, EditOperation.Identity, 0.0d); for (i = 1; i <= sourceObjectsCount; ++i) { matrix[i, 0] = new MatrixItem((double)i * _InsertDeleteCosts, EditOperation.Delete, 0.0d); } for (j = 1; j <= targetObjectsCount; ++j) { matrix[0, j] = new MatrixItem((double)j * _InsertDeleteCosts, EditOperation.Insert, 0.0d); } for (i = 1; i <= sourceObjectsCount; ++i) { for (j = 1; j <= targetObjectsCount; ++j) { matrix[i, j] = new MatrixItem(0.0d, EditOperation.Identity, 0.0d); } } // populate edit distance matrix for (i = 1; i <= sourceObjectsCount; ++i) { for (j = 1; j <= targetObjectsCount; ++j) { double similarity = sim[srcRange.Start + i - 1, trgRange.Start + j - 1]; System.Diagnostics.Debug.Assert((similarity >= 0.0d && similarity <= 1.0d) || similarity == -1.0d); // low similarity means high "change costs" and vice versa: double changeCosts = (similarity < 0) ? invalidAssignmentCosts : matrix[i - 1, j - 1].Score + (1.0d - similarity); double insertCosts = matrix[i, j - 1].Score + _InsertDeleteCosts; double deleteCosts = matrix[i - 1, j].Score + _InsertDeleteCosts; double min = Math.Min(Math.Min(changeCosts, deleteCosts), insertCosts); matrix[i, j].Score = min; matrix[i, j].Similarity = similarity; if (min == deleteCosts) { matrix[i, j].Operation = EditOperation.Delete; } else if (min == insertCosts) { matrix[i, j].Operation = EditOperation.Insert; } else if (min == changeCosts) { if (similarity == 1.0d) { matrix[i, j].Operation = EditOperation.Identity; } else { matrix[i, j].Operation = EditOperation.Change; } } } } // readout the cheapest path i = sourceObjectsCount; j = targetObjectsCount; // TODO we may rather need to find the end point at the borders result.Distance += matrix[i, j].Score; while (i > 0 || j > 0) { EditDistanceItem item = new EditDistanceItem(); item.Resolution = EditDistanceResolution.None; MatrixItem m = matrix[i, j]; item.Operation = m.Operation; switch (item.Operation) { case EditOperation.Identity: item.Costs = 0.0d; --i; --j; break; case EditOperation.Change: item.Costs = (1.0d - m.Similarity); --i; --j; break; case EditOperation.Insert: item.Costs = _InsertDeleteCosts; --j; break; case EditOperation.Delete: item.Costs = _InsertDeleteCosts; --i; break; } System.Diagnostics.Debug.Assert(i >= 0 && j >= 0); System.Diagnostics.Debug.Assert(sourceObjectsCount == 0 || item.Operation == EditOperation.Insert || i < sourceObjectsCount); System.Diagnostics.Debug.Assert(targetObjectsCount == 0 || item.Operation == EditOperation.Delete || j < targetObjectsCount); // TODO shift only for certain ops? item.Source = srcRange.Start + i; item.Target = trgRange.Start + j; result.AddAtStart(item); } return(result); }
public void VoegItemToeTest([PexAssumeUnderTest] Matrix target, MatrixItem matrixItem) { target.VoegItemToe(matrixItem); // TODO: add assertions to method MatrixTest.VoegItemToeTest(Matrix, MatrixItem) }
/// <summary> /// Computes and returns the edit distance between two sequences of type <typeparamref name="T"/>, using /// the similarity computer and cost values specified in the constructor. If <see cref="ComputeMoveOperations"/> /// is <c>true</c>, simple moves will be detected. Otherwise, moves will (typically) result in two independent /// insert/delete operations. /// </summary> /// <param name="sourceObjects">The first input sequence ("source")</param> /// <param name="targetObjects">The second input sequence ("target")</param> /// <param name="precomputedAssociations">A list of precomputed item index associations. If valid, item pairs /// in this list will be associated with each other, which will result in either an identity /// or a change operation.</param> /// <returns>The edit distance between the two sequences</returns> public Core.EditDistance.EditDistance ComputeEditDistance(IList <T> sourceObjects, IList <T> targetObjects, List <Core.Pair <int> > precomputedAssociations) { const double invalidAssignmentCosts = 100000.0d; #if DEBUG if (typeof(T) != typeof(char)) { } #endif if (sourceObjects == null) { throw new ArgumentNullException("sourceObjects"); } if (targetObjects == null) { throw new ArgumentNullException("targetObjects"); } if (precomputedAssociations != null) { if (!SortAndValidate(precomputedAssociations, sourceObjects.Count, targetObjects.Count)) { System.Diagnostics.Debug.Assert(false, "Invalid preassignments"); precomputedAssociations = null; } } // TODO handle special cases (one/both of the arrays being empty/having no elements) // TODO use diagonal algorithm Core.EditDistance.EditDistance result = new Core.EditDistance.EditDistance(sourceObjects.Count, targetObjects.Count, 0.0d); MatrixItem[,] matrix = new MatrixItem[sourceObjects.Count + 1, targetObjects.Count + 1]; int i, j; bool usePreassignments = precomputedAssociations != null; // initialize matrix matrix[0, 0] = new MatrixItem(0.0d, Core.EditDistance.EditOperation.Identity, 0.0d); for (i = 1; i <= sourceObjects.Count; ++i) { matrix[i, 0] = new MatrixItem((double)i * _InsertDeleteCosts, Core.EditDistance.EditOperation.Delete, 0.0d); } for (j = 1; j <= targetObjects.Count; ++j) { matrix[0, j] = new MatrixItem((double)j * _InsertDeleteCosts, Core.EditDistance.EditOperation.Insert, 0.0d); } for (i = 1; i <= sourceObjects.Count; ++i) { for (j = 1; j <= targetObjects.Count; ++j) { matrix[i, j] = new MatrixItem(0.0d, Core.EditDistance.EditOperation.Identity, 0.0d); } } // populate matrix for (i = 1; i <= sourceObjects.Count; ++i) { T s = sourceObjects[i - 1]; int associatedTarget = usePreassignments ? GetSourcePreassignment(i - 1, precomputedAssociations) : -1; for (j = 1; j <= targetObjects.Count; ++j) { T t = targetObjects[j - 1]; double similarity = 0.0d; if (associatedTarget < 0 || associatedTarget == j - 1) { // no preassignment or items are correlated - use std sim similarity = _SimilarityComputer(s, t); } else { // there is a correlation with another item - don't allow change/identity similarity = -1.0d; } System.Diagnostics.Debug.Assert((similarity >= 0.0d && similarity <= 1.0d) || similarity == -1.0d); // low similarity means high "change costs" and vice versa: double changeCosts = (similarity < 0) ? invalidAssignmentCosts : matrix[i - 1, j - 1].Score + (1.0d - similarity); double insertCosts = matrix[i, j - 1].Score + _InsertDeleteCosts; double deleteCosts = matrix[i - 1, j].Score + _InsertDeleteCosts; double min = Math.Min(Math.Min(changeCosts, deleteCosts), insertCosts); matrix[i, j].Score = min; matrix[i, j].Similarity = similarity; if (min == deleteCosts) { matrix[i, j].Operation = Core.EditDistance.EditOperation.Delete; } else if (min == insertCosts) { matrix[i, j].Operation = Core.EditDistance.EditOperation.Insert; } else if (min == changeCosts) { if (similarity == 1.0d) { matrix[i, j].Operation = Core.EditDistance.EditOperation.Identity; } else { matrix[i, j].Operation = Core.EditDistance.EditOperation.Change; } } } } // readout the cheapest path i = sourceObjects.Count; j = targetObjects.Count; result.Distance = matrix[i, j].Score; while (i > 0 || j > 0) { EditDistanceItem item = new EditDistanceItem(); item.Resolution = EditDistanceResolution.None; item.Operation = matrix[i, j].Operation; switch (item.Operation) { case EditOperation.Identity: --i; --j; item.Costs = 0.0d; break; case EditOperation.Change: item.Costs = 1.0d - matrix[i, j].Similarity; --i; --j; break; case EditOperation.Insert: --j; item.Costs = _InsertDeleteCosts; break; case EditOperation.Delete: item.Costs = _InsertDeleteCosts; --i; break; } item.Source = i; item.Target = j; result.AddAtStart(item); } // identify move operations which are pairs of insert/delete operations in the shortest path. // Note that the comparision result is already in the matrix and we only care about identity. // TODO we may rather use a configurable threshold than identity (1.0) to catch move operations // of sufficiently similar items (e.g. case-insensitive) int moves = 0; // try to detect moves in case the move penalty is smaller than the sum of insert/delete penalties if (_ComputeMoveOperations) { // matrix[i, j].Similarity is the cached token similarity between source[i-1] and target[j-1] // TODO may need to restrict moves to undisputed corresponding items, i.e. those which // have only one row/column similarity maximum for (int index = 0; index < result.Items.Count; ++index) { EditOperation op = result[index].Operation; if (op == EditOperation.Delete || op == EditOperation.Insert) { int moveSource = 0; int moveTarget = 0; int moveSourceTarget = 0; int moveTargetSource = 0; // search in the remainder of the result list for a "compensating" operation int comp = 0; for (comp = index + 1; comp < result.Items.Count; ++comp) { if (result[comp].Operation == EditOperation.Insert && op == EditOperation.Delete && matrix[result[index].Source + 1, result[comp].Target + 1].Similarity >= _SimThreshold) { // source[result[index].Source] was deleted // target[result[comp].Target] was inserted moveSource = result[index].Source; moveSourceTarget = result[index].Target; moveTarget = result[comp].Target; moveTargetSource = result[comp].Source; break; } else if (result[comp].Operation == EditOperation.Delete && op == EditOperation.Insert && matrix[result[comp].Source + 1, result[index].Target + 1].Similarity >= _SimThreshold) { // source[result[comp].Source] was deleted // target[result[index].Target] was inserted moveSource = result[comp].Source; moveSourceTarget = result[comp].Target; moveTarget = result[index].Target; moveTargetSource = result[index].Source; break; } } // TODO take moveDistance into account, i.e. penalty depends on distance? Avoids // long-distance moves. if (comp < result.Items.Count) { // compensating operation found // TODO backtrack to find other compensating items? EditDistanceItem item = result[index]; item.Operation = EditOperation.Move; item.Source = moveSource; item.Target = moveTarget; item.MoveSourceTarget = moveSourceTarget; item.MoveTargetSource = moveTargetSource; // TODO update item similarity result.Items[index] = item; result.Items.RemoveAt(comp); ++moves; } } } } if (moves > 0) { // adjust score: substract moves * (deletionCosts + insertionCosts), add moves * moveCosts // TODO take moveDistance into account, i.e. penalty depends on distance? result.Distance -= (double)moves * (2.0d * _InsertDeleteCosts); result.Distance += (double)moves * _MoveCosts; } #if DEBUG && !SILVERLIGHT _DumpMatrix = false; // typeof(T) != typeof(char); if (_DumpMatrix) { // in debug mode, write matrix to a temp file in HTML format System.Environment.GetEnvironmentVariable("TEMP"); System.IO.StreamWriter wtr = new System.IO.StreamWriter(System.Environment.GetEnvironmentVariable("TEMP") + "/SimMatrix.html", false, System.Text.Encoding.UTF8); System.Web.UI.Html32TextWriter htmlWriter = new System.Web.UI.Html32TextWriter(wtr); htmlWriter.WriteFullBeginTag("html"); htmlWriter.WriteFullBeginTag("body"); htmlWriter.WriteBeginTag("table"); htmlWriter.WriteAttribute("border", "1"); for (j = -1; j <= targetObjects.Count; ++j) { htmlWriter.WriteFullBeginTag("tr"); for (i = -1; i <= sourceObjects.Count; ++i) { htmlWriter.WriteFullBeginTag("td"); if (i < 0) { // caption row if (j >= 0) { htmlWriter.Write("j={0}", j); if (j > 0) { htmlWriter.WriteFullBeginTag("br"); htmlWriter.WriteFullBeginTag("b"); htmlWriter.Write(targetObjects[j - 1].ToString()); htmlWriter.WriteEndTag("b"); } } } else if (j < 0) { // j < 0 but i >= 0 --> htmlWriter.Write("i={0}", i); if (i > 0) { htmlWriter.WriteFullBeginTag("br"); htmlWriter.WriteFullBeginTag("b"); htmlWriter.Write(sourceObjects[i - 1].ToString()); htmlWriter.WriteEndTag("b"); } } else { // content cell htmlWriter.Write("d={0}", matrix[i, j].Score); htmlWriter.WriteFullBeginTag("br"); htmlWriter.Write("s={0}", matrix[i, j].Similarity); htmlWriter.WriteFullBeginTag("br"); htmlWriter.Write("o={0}", matrix[i, j].Operation.ToString()); } htmlWriter.WriteEndTag("td"); } htmlWriter.WriteEndTag("tr"); } htmlWriter.WriteEndTag("table"); htmlWriter.WriteFullBeginTag("h2"); htmlWriter.Write("Result"); htmlWriter.WriteEndTag("h2"); htmlWriter.Write("Score = {0}", result.Distance); htmlWriter.WriteFullBeginTag("ol"); for (i = 0; i < result.Items.Count; ++i) { htmlWriter.WriteFullBeginTag("li"); htmlWriter.Write("{0}: s={1} t={2}", result[i].Operation.ToString(), result[i].Source, result[i].Target); } htmlWriter.WriteEndTag("ol"); htmlWriter.WriteEndTag("body"); htmlWriter.WriteEndTag("html"); htmlWriter.Close(); } #endif return(result); }
//--------------------------------------------------------------------------------------- //This function computes the Confident Matrix and Weight Matrix, forllowing the formulars //--------------------------------------------------------------------------------------- public void ComputeConfident(Predict_DAO_MCol dao) { dao.CLEAN_CONF_Matrix(); dao.CLEAN_WEIG_Matrix(); List <string> list_ClusterID = dao.getAllClusterID(); foreach (var item in list_ClusterID) { List <Transac> u_transacs = dao.getTransac_ForMatrix_ByClusterID_V2(item); if (u_transacs.Count > 0) { // Get QuantityMatrix - MC Dictionary <string, int> QM_dic_users = new Dictionary <string, int>(); Dictionary <string, int> QM_dic_items = new Dictionary <string, int>(); double[][] QuantityMatrix = Util.getQuantityMatrix_FromTransac_ByMetaItemID(u_transacs, out QM_dic_users, out QM_dic_items); if (QuantityMatrix[0].Length > 1) { // Compute Support One Item Matrix - MC double[] S = new double[QuantityMatrix[0].Length]; for (int j = 0; j < QuantityMatrix[0].Length; j++) { double count = 0.0; for (int i = 0; i < QuantityMatrix.Length; i++) { if (QuantityMatrix[i][j] > 0) { count++; } } S[j] = count; } // Compute Support Matrix - MC double[][] SupportMatrix = new double[QuantityMatrix[0].Length][]; for (int i = 0; i < QuantityMatrix[0].Length; i++) { SupportMatrix[i] = new double[QuantityMatrix[0].Length]; } for (int i = 0; i < QuantityMatrix.Length; i++) { for (int j = 0; j < QuantityMatrix[0].Length; j++) { for (int j2 = 0; j2 < QuantityMatrix[0].Length; j2++) { if (QuantityMatrix[i][j] > 0 & QuantityMatrix[i][j2] > 0 & j != j2) { SupportMatrix[j][j2]++; } } } } // Compute CONF Matrix - MC double[][] CONF = new double[QuantityMatrix[0].Length][]; for (int i = 0; i < QuantityMatrix[0].Length; i++) { CONF[i] = new double[QuantityMatrix[0].Length]; } for (int i = 0; i < QuantityMatrix[0].Length; i++) { for (int j = 0; j < QuantityMatrix[0].Length; j++) { if (i == j) { CONF[i][j] = 1.0; } else if (S[i] > 0) { CONF[i][j] = SupportMatrix[i][j] / S[i]; } } } // Compute WEIG Matrix - MC double[][] WEIG = new double[QuantityMatrix[0].Length][]; for (int i = 0; i < QuantityMatrix[0].Length; i++) { WEIG[i] = new double[QuantityMatrix[0].Length]; } for (int i = 0; i < QuantityMatrix[0].Length; i++) { for (int j = 0; j < QuantityMatrix[0].Length; j++) { if (i != j) { WEIG[i][j] = computeWEIG(i, j, SupportMatrix, QuantityMatrix); } } } // Save CONF Matrix - MC for (int i = 0; i < CONF.Length; i++) { for (int j = 0; j < CONF[0].Length; j++) { if (CONF[i][j] > 0) { MatrixItem matrixItem = new MatrixItem(); matrixItem.Row = Util.FindKeyByValue(QM_dic_items, i); matrixItem.Column = Util.FindKeyByValue(QM_dic_items, j); matrixItem.Cell = CONF[i][j]; matrixItem.ClusterID = item; dao.setCONF_Matrix(matrixItem); } } } // Save WEIG Matrix for (int i = 0; i < WEIG.Length; i++) { for (int j = 0; j < WEIG[0].Length; j++) { if (WEIG[i][j] > 0) { MatrixItem matrixItem = new MatrixItem(); matrixItem.Row = Util.FindKeyByValue(QM_dic_items, i); matrixItem.Column = Util.FindKeyByValue(QM_dic_items, j); matrixItem.Cell = WEIG[i][j]; matrixItem.ClusterID = item; dao.setWEIG_Matrix(matrixItem); } } } } } } }
public MyCombined() { hdrItm = new HeaderItem(); mtxItm = new MatrixItem(); }
//--------------------------------------------------------------------------------------- //This function computes the DISTANCE matrix and inserts it into the database //This is the distance between the two columns of the Rating Matrix //--------------------------------------------------------------------------------------- public void ComputeDIST(Predict_DAO_MCol dao) { //dao.CLEAN_DIST_Matrix(); List <string> list_ClusterID = dao.getAllClusterID(); foreach (var item in list_ClusterID) { Dictionary <string, int> RM_dic_users = new Dictionary <string, int>(); Dictionary <string, int> RM_dic_items = new Dictionary <string, int>(); // Compute ratting matrix List <MatrixItem> lstRMI = dao.getRattingMatrixItem_ByClusterID(item); double[][] RattingMatrix = Util.toMatrix_MatrixItem(lstRMI, out RM_dic_users, out RM_dic_items); if (RattingMatrix.Length > 0 & RM_dic_items.Count > 1) { double[][] DIST = new double[RattingMatrix[0].Length][]; for (int i = 0; i < RattingMatrix[0].Length; i++) { DIST[i] = new double[RattingMatrix[0].Length]; } // Compute DIST Matrix for (int i1 = 0; i1 < RattingMatrix[0].Length - 1; i1++) { for (int i2 = i1 + 1; i2 < RattingMatrix[0].Length; i2++) { double value = 0.0; for (int t = 0; t < RattingMatrix.Length; t++) { value += Math.Pow(RattingMatrix[t][i1] - RattingMatrix[t][i2], 2); } value = Math.Sqrt(value); DIST[i1][i2] = value; DIST[i2][i1] = value; } } if (DIST.Length > 0) { double max = DIST[0][0]; // Find Max for (int i = 0; i < DIST.Length; i++) { double localMax = DIST[i].Max(); if (localMax > max) { max = localMax; } } // Standardization if (max != 0) { for (int i = 0; i < DIST.Length; i++) { for (int j = 0; j < DIST[0].Length; j++) { DIST[i][j] /= max; } } } // Save to Database for (int i = 0; i < DIST.Length; i++) { for (int j = 0; j < DIST[0].Length; j++) { if (DIST[i][j] > 0) { MatrixItem matrixItem = new MatrixItem(); matrixItem.Row = Util.FindKeyByValue(RM_dic_items, i); matrixItem.Column = Util.FindKeyByValue(RM_dic_items, j); matrixItem.Cell = DIST[i][j]; matrixItem.ClusterID = item; dao.setDIST_Matrix(matrixItem); } } } } } } }
private void LoadCluster(Clustering_Users_DAO dao, Settings st, ref bool existTransac, string U_SubCategoryID, string categoryName, Dictionary <string, int> dic_users, Dictionary <string, int> dic_items, double[][] x) { if (x.Length > 0) { existTransac = true; // Clustering Data Cluster cluster = new Cluster(); Dictionary <int, int> clustered_Data = new Dictionary <int, int>(); cluster.addSetting(st.k, st.maxLoop, x, st.epsilon, st.Alpha, st.T, st.U_M); clustered_Data = cluster.Clustering(st.cluster_type); //if (clustered_Data.Count > 0) //{ // Mapping UserID to clustered Data Dictionary <string, int> mapped_Data = map_ID_to_Index(dic_users, clustered_Data); // Get Destination V double[][] v = cluster.getV(); // Add new data #region C1 - Ratting Matrix // Add Ratting Matrix for (int i = 0; i < x.Length; i++) { for (int j = 0; j < x[0].Length; j++) { if (x[i][j] > 0) { try { MatrixItem matrixItem = new MatrixItem(); matrixItem.ClusterID = categoryName + (mapped_Data[Util.FindKeyByValue(dic_users, i)] + 1); matrixItem.Row = Util.FindKeyByValue(dic_users, i); matrixItem.Column = Util.FindKeyByValue(dic_items, j); matrixItem.Cell = x[i][j]; dao.setRattingMatrix(matrixItem); } catch (Exception) { } } } } #endregion // Add to USER_CLUSTER_TBL for (int i = 0; i < v.Length; i++) { dao.addCluster(categoryName + (i + 1), U_SubCategoryID); } // Add to PARTION_TBL foreach (var map in mapped_Data) { Partion detail = new Partion(); detail.UserID = map.Key; detail.ClusterID = categoryName + (map.Value + 1); dao.addPARTION_TBL(detail); } // Add to USER_CENTROID_TBL for (int i = 0; i < v.Length; i++) { for (int j = 0; j < v[0].Length; j++) { if (!Double.NaN.Equals(v[i][j])) { try { User_Centroid centroid = new User_Centroid(); centroid.Value = v[i][j]; centroid.ClusterID = categoryName + (i + 1); centroid.MetaItemID = Util.FindKeyByValue(dic_items, j); dao.add_User_Centroid(centroid); } catch (Exception) { } } } } } //} }
private void LoadUpdateCluster(Clustering_Users_DAO dao, Settings st, ref bool existTransac, List <Partion> listPartion, string U_SubCategoryID, string categoryName, Dictionary <string, int> dic_users, Dictionary <string, int> dic_items, double[][] x) { if (x.Length > 0) { existTransac = true; List <string> listClusterID = getListClusterID(listPartion); // Get existed V double[][] v = new double[listClusterID.Count][]; Cluster cl = new Cluster(); cl.addSetting(v.Length, st.maxLoop, x, 0.0001, st.Alpha, st.T, st.U_M); Dictionary <int, int> clustered_Data; if (listPartion.Count > 0) { v = get_V_ByNewItems_ReComputeAll(x, dic_items, dic_users, listPartion, listClusterID); clustered_Data = cl.Clustering_Merge(st.cluster_type, v); } else { clustered_Data = cl.Clustering_Merge(st.cluster_type); } v = cl.getV(); // Mapping UserID to clustered Data Dictionary <string, int> mapped_Data = map_ID_to_Index(dic_users, clustered_Data); #region C1 - Ratting Matrix // Add Ratting Matrix for (int i = 0; i < x.Length; i++) { for (int j = 0; j < x[0].Length; j++) { if (x[i][j] > 0) { try { MatrixItem matrixItem = new MatrixItem(); matrixItem.ClusterID = categoryName + (mapped_Data[Util.FindKeyByValue(dic_users, i)] + 1); matrixItem.Row = Util.FindKeyByValue(dic_users, i); matrixItem.Column = Util.FindKeyByValue(dic_items, j); matrixItem.Cell = x[i][j]; dao.setRattingMatrix(matrixItem); } catch (Exception) { } } } } #endregion // Remove old USER_CLUSTER_TBL dao.delete_USER_CLUSTER_TBL(categoryName); // Add to USER_CLUSTER_TBL for (int i = 0; i < v.Length; i++) { dao.addCluster(categoryName + (i + 1), U_SubCategoryID); } // Remove old PARTION_TBL dao.delete_PARTION_TBL(categoryName); // Add to PARTION_TBL foreach (var map in mapped_Data) { Partion detail = new Partion(); detail.UserID = map.Key; detail.ClusterID = categoryName + (map.Value + 1); dao.addPARTION_TBL(detail); } // Remove old USER_CENTROID_TBL dao.delete_USER_CENTROID_TBL(categoryName); // Add to USER_CENTROID_TBL for (int i = 0; i < v.Length; i++) { for (int j = 0; j < v[0].Length; j++) { if (!Double.NaN.Equals(v[i][j])) { try { User_Centroid centroid = new User_Centroid(); centroid.Value = v[i][j]; centroid.ClusterID = categoryName + (i + 1); centroid.MetaItemID = Util.FindKeyByValue(dic_items, j); dao.add_User_Centroid(centroid); } catch (Exception) { } } } } } }