-
Notifications
You must be signed in to change notification settings - Fork 1
/
myVector.cs
181 lines (156 loc) · 5.42 KB
/
myVector.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Linq;
using System.Globalization;
[Serializable]
[SqlUserDefinedType(Format.UserDefined, IsByteOrdered = true, MaxByteSize = -1)]
public class Vector : INullable, IBinarySerialize
{
private float[] _values;
// Default constructor
public Vector()
{
_values = Array.Empty<float>();
}
public int Size()
{
return _values.Length;
}
public bool IsNull { get; private set; }
public static Vector Null
{
get
{
var vector = new Vector { IsNull = true };
return vector;
}
}
// Parse from a comma-delimited string or a simple JSON-like format
public static Vector Parse(SqlString input)
{
if (input.IsNull || string.IsNullOrWhiteSpace(input.Value))
return Null;
var vector = new Vector();
string inputValue = input.Value.Trim();
try
{
if (inputValue.StartsWith("[") && inputValue.EndsWith("]"))
{
// Remove initial and final brackets
string trimmedInput = inputValue.Substring(1, inputValue.Length - 2);
// Split elements by commas and convert them to float
vector._values = trimmedInput
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(v => float.Parse(v, CultureInfo.InvariantCulture))
.ToArray();
}
else
{
// if it is not JSON-like, interpret as a comma separated list
vector._values = inputValue
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(v => float.Parse(v, CultureInfo.InvariantCulture))
.ToArray();
}
}
catch (FormatException)
{
throw new ArgumentException("Invalid input format.");
}
vector.IsNull = false;
return vector;
}
public override string ToString()
{
if (_values == null || _values.Length == 0)
return "[]";
// Format values and join them in a single line
var formattedValues = _values
.Select(v => v.ToString("e7", CultureInfo.InvariantCulture)) // Always use '.' as separator
.ToArray();
return "[" + string.Join(",", formattedValues) + "]";
}
// Methods for binary serialization (IBinarySerialize)
public void Read(System.IO.BinaryReader reader)
{
int length = reader.ReadInt32();
_values = new float[length];
for (int i = 0; i < length; i++)
{
_values[i] = reader.ReadSingle();
}
}
public void Write(System.IO.BinaryWriter writer)
{
writer.Write(_values.Length);
foreach (var value in _values)
{
writer.Write(value);
}
}
// Function to calculate distance between two vectors
public static SqlSingle VectorDistance(string distanceMetric, Vector vector1, Vector vector2)
{
if (vector1.IsNull == true || vector2.IsNull == true)
{
return SqlSingle.Null;
}
if (vector1._values.Length != vector2._values.Length)
{
throw new ArgumentException($"The vector dimensions {vector1._values.Length} and {vector2._values.Length} do not match.");
}
distanceMetric = distanceMetric.ToLower();
switch (distanceMetric)
{
case "cosine":
return new SqlSingle(CosineDistance(vector1._values, vector2._values));
case "euclidean":
return new SqlSingle(EuclideanDistance(vector1._values, vector2._values));
case "dot":
return new SqlSingle(-DotProduct(vector1._values, vector2._values));
case "manhattan":
return new SqlSingle(ManhattanDistance(vector1._values, vector2._values));
default:
throw new ArgumentException($"Unsupported distance metric: {distanceMetric}");
}
}
// Distance methods and operations between vectors...
private static float CosineDistance(float[] v1, float[] v2)
{
float dot = DotProduct(v1, v2);
float norm1 = (float)Math.Sqrt(DotProduct(v1, v1));
float norm2 = (float)Math.Sqrt(DotProduct(v2, v2));
if (norm1 == 0 || norm2 == 0)
return 1.0f;
return 1.0f - (dot / (norm1 * norm2));
}
private static float EuclideanDistance(float[] v1, float[] v2)
{
float sum = 0.0f;
for (int i = 0; i < v1.Length; i++)
{
float diff = v1[i] - v2[i];
sum += diff * diff;
}
return (float)Math.Sqrt(sum);
}
private static float DotProduct(float[] v1, float[] v2)
{
float result = 0.0f;
for (int i = 0; i < v1.Length; i++)
{
result += v1[i] * v2[i];
}
return result;
}
private static float ManhattanDistance(float[] v1, float[] v2)
{
float distance = 0.0f;
for (int i = 0; i < v1.Length; i++)
{
distance += Math.Abs(v1[i] - v2[i]);
}
return distance;
}
}