Skip to content

Commit

Permalink
Added dictionary constructor for SparseVector
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Jun 21, 2024
1 parent 4c190c0 commit 18129ab
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/Pgvector/SparseVector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,28 @@ public SparseVector(ReadOnlyMemory<float> v)
Values = values.ToArray();
}

public SparseVector(IDictionary<int, float> dictionary, int dimensions)
{
List<KeyValuePair<int, float>> elements = dictionary.ToList();
elements.Sort((a, b) => a.Key.CompareTo(b.Key));

var indices = new List<int>();
var values = new List<float>();

foreach (KeyValuePair<int, float> e in elements)
{
if (e.Value != 0)
{
indices.Add(e.Key);
values.Add(e.Value);
}
}

Dimensions = dimensions;
Indices = indices.ToArray();
Values = values.ToArray();
}

public SparseVector(string s)
{
var parts = s.Split('/', 2);
Expand Down
13 changes: 13 additions & 0 deletions tests/Pgvector.CSharp.Tests/SparseVectorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,17 @@ public void ArrayConstructor()
var v = new SparseVector(new float[] { 1, 0, 2, 0, 3, 0 });
Assert.Equal(new float[] { 1, 0, 2, 0, 3, 0 }, v.ToArray());
}

[Fact]
public void DictionaryConstructor()
{
var dictionary = new Dictionary<int, float>();
dictionary.Add(2, 2);
dictionary.Add(4, 3);
dictionary.Add(0, 1);
dictionary.Add(3, 0);
var v = new SparseVector(dictionary, 6);
Assert.Equal(new float[] { 1, 0, 2, 0, 3, 0 }, v.ToArray());
Assert.Equal(new int[] { 0, 2, 4 }, v.Indices.ToArray());
}
}

0 comments on commit 18129ab

Please sign in to comment.