private Boolean SaveMatrix(String fileName, Double[,] matrix) { try { StreamWriter sw = File.CreateText(fileName); for (Int32 y = 0; y < matrix.GetLength(1); y++) { for (Int32 x = 0; x < matrix.GetLength(0); x++) { sw.Write(matrix[x, y].ToString(System.Globalization.CultureInfo.InvariantCulture)); sw.Write(" "); } sw.Write(Environment.NewLine); } sw.Close(); } catch { MessageBox.Show("Error while saving the matrix to a file! Please check the path!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } return true; }
static void Output(Double[,] a) { for (Int32 i = 0; i < a.GetLength(0); i++) { for (Int32 j = 0; j < a.GetLength(1); j++) { Console.Write(a[i, j].ToString() + ","); } Console.WriteLine(); } }
public static Term[,] matrix(Double[,] m) { int rows = m.GetLength(0); int cols = m.GetLength(1); Term[,] r = new Term[rows, cols]; for (int row = 0; row < rows; row++) for (int col = 0; col < cols; col++) r[row, col] = m[row, col]; return r; }
public XLMatrix(Double[,] arr) :this(arr.GetLength(0), arr.GetLength(1)) { var roCount = arr.GetLength(0); var coCount = arr.GetLength(1); for (int ro = 0; ro < roCount; ro++) { for (int co = 0; co < coCount; co++) { mat[ro, co] = arr[ro, co]; } } }
public static void Main() { // define cost matrix Double INF = Double.PositiveInfinity; /* Double[,] costMatrix = new Double[,] { { INF, 2.0, 4.0, 22.0, 2.0, INF}, { 2.0, INF, 8.0, 15.0, 13.0, 10.0}, { 4.0, 8.0, INF, 5.0, 2.0, INF}, {22.0, 15.0, 5.0, INF, 11.0, 12.0}, { 2.0, 13.0, 2.0, 11.0, INF, 14.0}, { INF, 10.0, INF, 12.0, 14.0, INF}, }; */ Double[,] costMatrix = new Double[,] { { INF, 2.0, INF, INF, 7.0}, { 2.0, INF, 1.0, 3.0, INF}, { INF, 1.0, INF, 1.0, 5.0}, { INF, 3.0, 1.0, INF, INF}, { 7.0, INF, 5.0, INF, INF}, }; costMatrix = new Double[,] { { INF, 20.0, INF, 70.0}, { 20.0, INF, 40.0, INF}, { INF, 40.0, INF,50.0}, { 70.0, INF, 50.0,INF}, }; // create prototype chromosome PermutationChromosome prototype = new PermutationChromosome(0, costMatrix.GetLength(0) - 1); // set prototype's parameters prototype.CrossOverStrategy = new PermutationChromosome.CycleCrossOverStrategy(); prototype.RandomGenerator = new ThreadSafeRandomGenerator(); prototype.MutationStrategy = new PermutationChromosome.InsertMutationStrategy(); prototype.Fitness = new TSPFitness(costMatrix); // stop condition, keep reference for selecting the leader NoChangeStopCondion stopCondition = new NoChangeStopCondion(10); // create population DefaultPopulation population = new DefaultPopulation(prototype, 40); // set population's parameters population.SelectionStrategy = new StochasticUniversalSamplingStrategy(new FixedSizeStrategy(40), new ThreadSafeRandomGenerator()); population.RandomGenerator = new ThreadSafeRandomGenerator(); population.StopCondition = stopCondition; // perform util the stop condition returns false while (population.NextGeneration()) ; // print the result System.Console.WriteLine("Best fitness: " + (1.0 / stopCondition.Leader.Evaluate())); System.Console.WriteLine(stopCondition.Leader.ToString()); System.Console.ReadKey(); }
/* Takes a graph as input an adjacency matrix (see top for details) and a starting node */ public BellmanFord(Double[,] G,List<Edge> edge, int s) { int u, v; /* Check graph format and that the graph actually contains something */ if (G.GetLength(0) < 1 || G.GetLength(0) != G.GetLength(1)) { throw new ArgumentException("Graph error, wrong format or no nodes to compute"); } int len = G.GetLength(0); /* foreach(Vertex v in vertices) { if (v.ident == s) v.dist = 0; else {v.dist = int.MaxValue; v.pre = null;} } */ Initialize(s, len); // for (i = 1; i <= sizeof(vertices) - 1; i++); while (queue > 0) { queue = queue - 1; /* Find the nodes that u connects to and perform relax */ foreach (Edge uv in edge) { u = uv.from; v = uv.to; /* Edge exists, relax the edge */ if (dist[u] + G[u, v] < dist[v]) { dist[v] = dist[u] + G[u, v]; path[v] = u; } } } /* Checks for edges with negative weight */ foreach (Edge vu in edge) { u = vu.from; v = vu.to; if (G[u,v] < 0) throw new ArgumentException("Graph contains negative edge(s)"); // if (dist[u] + G[u, v] < dist[v]) throw new ArgumentException("Graph contains negative edge(s)"); } }
public static string printMatrix(Double[,] matrix) { int rowLength = matrix.GetLength(0); int colLength = matrix.GetLength(1); StringBuilder builder = new StringBuilder(); for (int i = 0; i < rowLength; i++) { for (int j = 0; j < colLength; j++) { Console.Write(string.Format("{0} ", matrix[i, j])); builder.Append(string.Format("{0} ", matrix[i, j])); } Console.Write(Environment.NewLine + Environment.NewLine); builder.Append(Environment.NewLine + Environment.NewLine); } builder.Append("\n\n"); return builder.ToString(); }
private void WriteAccuracy(Double[,] result) { var p_size = result.GetLength(0); var d_size = result.GetLength(1); using (var writer = new StreamWriter("../Accuracy.cs")) { writer.WriteLine("namespace CloudBall.Engines.Toothless"); writer.WriteLine("{"); writer.WriteLine(" public partial class Statistics"); writer.WriteLine(" {"); writer.WriteLine(" private static readonly float[,] Accuracy = new float[,]{"); for (var p = 0; p < p_size; p++) { writer.Write("{{ {0:0.000}f /* {1:00.0}° */", result[p, 0], ToAngle(result[p, 0])); for (var d = 1; d < d_size; d++) { writer.Write(", {0:0.000}f /* {1:00.0}° */", result[p, d], ToAngle(result[p, d])); } writer.WriteLine(" },"); } writer.WriteLine("};}}"); } }
/// <summary> /// Prints the provided multi-dimentional array to a csv file with the given filename /// </summary> /// <param name='data'> /// Data. /// </param> /// <param name='fileName'> /// File name. /// </param> public static void PrintArrayToFile(Double[][] data, String fileName) { using (StreamWriter stream = File.CreateText(fileName)) { for (Int32 x = 0; x < data.GetLength(0); x++) { for (Int32 y = 0; y < data[x].GetLength(0); y++) { if (y + 1 < data[x].GetLength(0)) stream.Write(data[x][y] + ","); else stream.Write(data[x][y]); } stream.WriteLine(""); } } }
public static String PrintArrayToString(Double[][] data) { StringBuilder theString = new StringBuilder(); for (Int32 x = 0; x < data.GetLength(0); x++) { for (Int32 y = 0; y < data[x].GetLength(0); y++) { if (y + 1 < data[x].GetLength(0)) theString.Append(data[x][y] + ","); else theString.Append(data[x][y]); } theString.AppendLine(); } return theString.ToString(); }
public static bool IsEqual(this Int16[][] a, Double[][] b, Double atol = 0, Double rtol = 0) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; int[] la = a.GetLength(true); int[] lb = b.GetLength(true); if (la.Length != lb.Length) return false; for (int i = 0; i < la.Length; i++) if (la[i] != lb[i]) return false; if (rtol > 0) { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; if (A == B) continue; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; var C = A; var D = B; var delta = Math.Abs(C - D); if (C == 0) { if (delta <= rtol) continue; } else if (D == 0) { if (delta <= rtol) continue; } if (delta <= Math.Abs(C) * rtol) continue; return false; } } else if (atol > 0) { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; if (A == B) continue; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; var C = A; var D = B; if (Math.Abs(C - D) <= atol) continue; return false; } } else { for (int i = 0; i < a.Length; i++) for (int j = 0; j < a[i].Length; j++) { var A = a[i][j]; var B = b[i][j]; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; if (A != B) return false; } } return true; }
public static bool IsEqual(this sbyte[,] a, Double[,] b, Double atol = 0, Double rtol = 0) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; int[] la = a.GetLength(true); int[] lb = b.GetLength(true); if (la.Length != lb.Length) return false; for (int i = 0; i < la.Length; i++) if (la[i] != lb[i]) return false; unsafe { fixed (sbyte* ptrA = a) fixed (Double* ptrB = b) { if (rtol > 0) { for (int i = 0; i < a.Length; i++) { var A = ptrA[i]; var B = ptrB[i]; if (A == B) continue; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; var C = A; var D = B; var delta = Math.Abs(C - D); if (C == 0) { if (delta <= rtol) continue; } else if (D == 0) { if (delta <= rtol) continue; } if (delta <= Math.Abs(C) * rtol) continue; return false; } } else if (atol > 0) { for (int i = 0; i < a.Length; i++) { var A = ptrA[i]; var B = ptrB[i]; if (A == B) continue; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; var C = A; var D = B; if (Math.Abs(C - D) <= atol) continue; return false; } } else { for (int i = 0; i < a.Length; i++) { var A = ptrA[i]; var B = ptrB[i]; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; if (A != B) return false; } } } } return true; }
public static bool IsEqual(this Decimal[,] a, Double[][] b, Decimal atol = 0, Decimal rtol = 0) { if (a == null && b == null) return true; if (a == null ^ b == null) return false; int[] la = a.GetLength(true); int[] lb = b.GetLength(true); if (la.Length != lb.Length) return false; for (int i = 0; i < la.Length; i++) if (la[i] != lb[i]) return false; if (rtol > 0) { for (int i = 0; i < b.Length; i++) for (int j = 0; j < b[i].Length; j++) { var A = a[i, j]; var B = b[i][j]; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; decimal C = (decimal)A; decimal D = (decimal)B; if (C == D) continue; var delta = Math.Abs(C - D); if (C == 0) { if (delta <= rtol) continue; } else if (D == 0) { if (delta <= rtol) continue; } if (delta <= Math.Abs(C) * rtol) continue; return false; } } else if (atol > 0) { for (int i = 0; i < b.Length; i++) for (int j = 0; j < b[i].Length; j++) { var A = a[i, j]; var B = b[i][j]; if (Double.IsNaN(B)) return false; if (Double.IsInfinity(B)) return false; decimal C = (decimal)A; decimal D = (decimal)B; if (C == D) continue; if (Math.Abs(C - D) <= atol) continue; return false; } } else { for (int i = 0; i < b.Length; i++) for (int j = 0; j < b[i].Length; j++) { var A = (decimal)a[i, j]; var B = (decimal)b[i][j]; if (A != B) return false; } } return true; }
public static void Map3D(MappingMode mappingMode, Double[, ,] array, ImplicitModuleBase module, MappingRanges ranges) { var width = array.GetLength(0); var height = array.GetLength(1); var depth = array.GetLength(2); for (var x = 0; x < width; ++x) { for (var y = 0; y < height; ++y) { for (var z = 0; z < depth; ++z) { var p = x / (Double)width; var q = y / (Double)height; var r = z / (Double)depth; Double nx; Double ny; Double nz; Double nw; Double nu; Double dx; Double dy; Double dz; var val = 0.0; switch (mappingMode) { case MappingMode.SeamlessNone: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.MapY1 - ranges.MapY0; dz = ranges.MapZ1 - ranges.MapZ0; nx = ranges.MapX0 + p * dx; ny = ranges.MapY0 + q * dy; nz = ranges.MapZ0 + r * dz; val = module.Get(nx, ny, nz); break; case MappingMode.SeamlessX: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.MapY1 - ranges.MapY0; dz = ranges.MapZ1 - ranges.MapZ0; p = p * (ranges.MapX1 - ranges.MapX0) / (ranges.LoopX1 - ranges.LoopX0); nx = ranges.LoopX0 + Math.Cos(p * PI2) * dx / PI2; ny = ranges.LoopX0 + Math.Sin(p * PI2) * dx / PI2; nz = ranges.MapY0 + q * dy; nw = ranges.MapZ0 + depth * dz; val = module.Get(nx, ny, nz, nw); break; case MappingMode.SeamlessY: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.LoopY1 - ranges.LoopY0; dz = ranges.MapZ1 - ranges.MapZ0; q = q * (ranges.MapY1 - ranges.MapY0) / (ranges.LoopY1 - ranges.LoopY0); nx = ranges.MapX0 + p * dx; ny = ranges.LoopY0 + Math.Cos(q * PI2) * dy / PI2; nz = ranges.LoopY0 + Math.Sin(q * PI2) * dy / PI2; nw = ranges.MapZ0 + r * dz; val = module.Get(nx, ny, nz, nw); break; case MappingMode.SeamlessZ: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.MapY1 - ranges.MapY0; dz = ranges.LoopZ1 - ranges.LoopZ0; r = r * (ranges.MapZ1 - ranges.MapZ0) / (ranges.LoopZ1 - ranges.LoopZ0); nx = ranges.MapX0 + p * dx; ny = ranges.MapY0 + q * dy; nz = ranges.LoopZ0 + Math.Cos(r * PI2) * dz / PI2; nw = ranges.LoopZ0 + Math.Sin(r * PI2) * dz / PI2; val = module.Get(nx, ny, nz, nw); break; case MappingMode.SeamlessXY: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.LoopY1 - ranges.LoopY0; dz = ranges.MapZ1 - ranges.MapZ0; p = p * (ranges.MapX1 - ranges.MapX0) / (ranges.LoopX1 - ranges.LoopX0); q = q * (ranges.MapY1 - ranges.MapY0) / (ranges.LoopY1 - ranges.LoopY0); nx = ranges.LoopX0 + Math.Cos(p * PI2) * dx / PI2; ny = ranges.LoopX0 + Math.Sin(p * PI2) * dx / PI2; nz = ranges.LoopY0 + Math.Cos(q * PI2) * dy / PI2; nw = ranges.LoopY0 + Math.Sin(q * PI2) * dy / PI2; nu = ranges.MapZ0 + r * dz; val = module.Get(nx, ny, nz, nw, nu, 0); break; case MappingMode.SeamlessXZ: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.MapY1 - ranges.MapY0; dz = ranges.LoopZ1 - ranges.LoopZ0; p = p * (ranges.MapX1 - ranges.MapX0) / (ranges.LoopX1 - ranges.LoopX0); r = r * (ranges.MapZ1 - ranges.MapZ0) / (ranges.LoopZ1 - ranges.LoopZ0); nx = ranges.LoopX0 + Math.Cos(p * PI2) * dx / PI2; ny = ranges.LoopX0 + Math.Sin(p * PI2) * dx / PI2; nz = ranges.MapY0 + q * dy; nw = ranges.LoopZ0 + Math.Cos(r * PI2) * dz / PI2; nu = ranges.LoopZ0 + Math.Sin(r * PI2) * dz / PI2; val = module.Get(nx, ny, nz, nw, nu, 0); break; case MappingMode.SeamlessYZ: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.LoopY1 - ranges.LoopY0; dz = ranges.LoopZ1 - ranges.LoopZ0; q = q * (ranges.MapY1 - ranges.MapY0) / (ranges.LoopY1 - ranges.LoopY0); r = r * (ranges.MapZ1 - ranges.MapZ0) / (ranges.LoopZ1 - ranges.LoopZ0); nx = ranges.MapX0 + p * dx; ny = ranges.LoopY0 + Math.Cos(q * PI2) * dy / PI2; nz = ranges.LoopY0 + Math.Sin(q * PI2) * dy / PI2; nw = ranges.LoopZ0 + Math.Cos(r * PI2) * dz / PI2; nu = ranges.LoopZ0 + Math.Sin(r * PI2) * dz / PI2; val = module.Get(nx, ny, nz, nw, nu, 0); break; case MappingMode.SeamlessXYZ: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.LoopY1 - ranges.LoopY0; dz = ranges.LoopZ1 - ranges.LoopZ0; p = p * (ranges.MapX1 - ranges.MapX0) / (ranges.LoopX1 - ranges.LoopX0); q = q * (ranges.MapY1 - ranges.MapY0) / (ranges.LoopY1 - ranges.LoopY0); r = r * (ranges.MapZ1 - ranges.MapZ0) / (ranges.LoopZ1 - ranges.LoopZ0); nx = ranges.LoopX0 + Math.Cos(p * PI2) * dx / PI2; ny = ranges.LoopX0 + Math.Sin(p * PI2) * dx / PI2; nz = ranges.LoopY0 + Math.Cos(q * PI2) * dy / PI2; nw = ranges.LoopY0 + Math.Sin(q * PI2) * dy / PI2; nu = ranges.LoopZ0 + Math.Cos(r * PI2) * dz / PI2; Double nv = ranges.LoopZ0 + Math.Sin(r * PI2) * dz / PI2; val = module.Get(nx, ny, nz, nw, nu, nv); break; } array[x, y, z] = val; } } } }
public static Double StandardDeviation(Double[,] numbers, Int32 columnIndex) { if (numbers == null) throw new ArgumentNullException("numbers"); Int32 length = numbers.GetLength(0); var row = new Double[length]; for (Int32 i = 0; i < length; i++) row[i] = numbers[i, columnIndex]; return StandardDeviation(row); }
/// <summary> /// Constructs a new matrix based on the given two dimensional array. /// </summary> /// <param name="values">The values which set the dimensions and starting values of the matrix.</param> public MatrixValue(Double[,] values) : this(values.GetLength(0), values.GetLength(1)) { for (var j = 0; j < _dimY; j++) { for (var i = 0; i < _dimX; i++) { if (values[j, i] != 0.0) { this[j + 1, i + 1] = new ScalarValue(values[j, i]); } } } }
private Double[][] Desnormalizar(Double[][] vectoresEncontrados) { Double[][] vectorDesnormalizado = new Double[vectoresEncontrados.GetLength(0)][]; Double[][] maxYmin = csvtoMatrix("maxYmin"); int alto = vectoresEncontrados.Length; for (int i = 0; i < alto; i++) { Double[] fila = new Double[10]; for (int j = 0; j < 10; j++) { fila[j] = (vectoresEncontrados[i][j] * (maxYmin[0][j] - maxYmin[1][j])) + maxYmin[1][j]; } vectorDesnormalizado[i] = fila; } return vectorDesnormalizado; }
/// <summary> /// Wstawia dane do kontrolki je wyświetlającej. /// </summary> private void InsertData(Double[,] dane) { StringBuilder builder = new StringBuilder(); dataListBox.Items.Clear(); for (Int32 i = 0; i < dane.GetLength(0); i++) { for (Int32 j = 0; j < dane.GetLength(1); j++) { Double d = dane[i, j]; if (Double.IsInfinity(d)) builder.Append("INF"); else builder.Append(d); builder.Append('\t'); } dataListBox.Items.Add(builder.ToString()); builder.Clear(); } }
private void WriteAccuracy(Double[,] result) { var p_size = result.GetLength(0); var d_size = result.GetLength(1); using (var writer = new StreamWriter("../Accuracy.cs")) { writer.WriteLine("{"); for (var p = 0; p < p_size; p++) { writer.Write("{{ {0:0.000}f /* {1:00.0}° */", result[p, 0], ToAngle(result[p, 0])); for (var d = 1; d < d_size; d++) { writer.Write(", {0:0.000}f /* {1:00.0}° */", result[p, d], ToAngle(result[p, d])); } writer.WriteLine(" },"); } writer.WriteLine("};"); } }
private Double[,] InverseDCT(Double[,] input) { double sqrtOfLength = System.Math.Sqrt(input.Length); int N = input.GetLength(0); Double[,] coefficientsMatrix = this.quantizationMatrixForStandardJPEG(); Double[,] output = new Double[N, N]; for (int x = 0; x <= N - 1; x++) { for (int y = 0; y <= N - 1; y++) { double sum = 0.0; for (int u = 0; u <= N - 1; u++) { for (int v = 0; v <= N - 1; v++) { sum += coefficientsMatrix[u, v] * input[u, v] * System.Math.Cos(((2.0 * x + 1.0) / (2.0 * N)) * u * System.Math.PI) * System.Math.Cos(((2.0 * y + 1.0) / (2.0 * N)) * v * System.Math.PI); } }; output[x, y] = System.Math.Round(sum); } } return output; }
private Double[,] v; // right singular vectors #endregion Fields #region Constructors /// <summary>Constructs a new singular value decomposition.</summary> /// <param name="value"> /// The matrix to be decomposed.</param> public SingularValueDecomposition(Double[,] value) { if (value == null) { throw new ArgumentNullException("value", "Matrix cannot be null."); } //m should not less than n Double[,] a; m = value.GetLength(0); // rows n = value.GetLength(1); // cols if (m < n) { throw new System.Exception("rows should not less than cols in value matrix"); } // Proceed anyway a = (Double[,])value.Clone(); int nu = System.Math.Min(m, n); int ni = System.Math.Min(m + 1, n); s = new Double[ni]; u = new Double[m, nu]; v = new Double[n, n]; Double[] e = new Double[n]; Double[] work = new Double[m]; // Will store ordered sequence of indices after sorting. si = new int[ni]; for (int i = 0; i < ni; i++) si[i] = i; // Reduce A to bidiagonal form, storing the diagonal elements in s and the super-diagonal elements in e. int nct = System.Math.Min(m - 1, n); int nrt = System.Math.Max(0, System.Math.Min(n - 2, m)); for (int k = 0; k < System.Math.Max(nct, nrt); k++) { if (k < nct) { // Compute the transformation for the k-th column and place the k-th diagonal in s[k]. // Compute 2-norm of k-th column without under/overflow. s[k] = 0; for (int i = k; i < m; i++) { s[k] = Hypotenuse(s[k], a[i, k]); } if (s[k] != 0) { if (a[k, k] < 0) s[k] = -s[k]; for (int i = k; i < m; i++) a[i, k] /= s[k]; a[k, k] += 1; } s[k] = -s[k]; } for (int j = k + 1; j < n; j++) { if ((k < nct) & (s[k] != 0)) { // Apply the transformation. Double t = 0; for (int i = k; i < m; i++) { t += a[i, k] * a[i, j]; } t = -t / a[k, k]; for (int i = k; i < m; i++) { a[i, j] += t * a[i, k]; } } // Place the k-th row of A into e for the subsequent calculation of the row transformation. e[j] = a[k, j]; } if (k < nct) { // Place the transformation in U for subsequent back // multiplication. for (int i = k; i < m; i++) u[i, k] = a[i, k]; } if (k < nrt) { // Compute the k-th row transformation and place the k-th super-diagonal in e[k]. // Compute 2-norm without under/overflow. e[k] = 0; for (int i = k + 1; i < n; i++) e[k] = Hypotenuse(e[k], e[i]); if (e[k] != 0) { if (e[k + 1] < 0) e[k] = -e[k]; for (int i = k + 1; i < n; i++) e[i] /= e[k]; e[k + 1] += 1; } e[k] = -e[k]; if ((k + 1 < m) & (e[k] != 0)) { // Apply the transformation. for (int i = k + 1; i < m; i++) work[i] = 0; int k1 = k + 1; for (int i = k1; i < m; i++) { for (int j = k1; j < n; j++) { work[i] += e[j] * a[i, j]; } } for (int j = k1; j < n; j++) { Double t = -e[j] / e[k1]; for (int i = k1; i < m; i++) { a[i, j] += t * work[i]; } } } // Place the transformation in V for subsequent back multiplication. for (int i = k + 1; i < n; i++) v[i, k] = e[i]; } } // Set up the final bidiagonal matrix or order p. int p = System.Math.Min(n, m + 1); if (nct < n) s[nct] = a[nct, nct]; if (m < p) s[p - 1] = 0; if (nrt + 1 < p) e[nrt] = a[nrt, p - 1]; e[p - 1] = 0; //generate U. for (int j = nct; j < nu; j++) { for (int i = 0; i < m; i++) u[i, j] = 0; u[j, j] = 1; } for (int k = nct - 1; k >= 0; k--) { if (s[k] != 0) { for (int j = k + 1; j < nu; j++) { Double t = 0; for (int i = k; i < m; i++) { t += u[i, k] * u[i, j]; } t = -t / u[k, k]; for (int i = k; i < m; i++) { u[i, j] += t * u[i, k]; } } for (int i = k; i < m; i++) { u[i, k] = -1.0 * u[i, k]; } u[k, k] = 1 + u[k, k]; for (int i = 0; i < k - 1; i++) u[i, k] = 0; } else { for (int i = 0; i < m; i++) u[i, k] = 0; u[k, k] = 1; } } //generate V. for (int k = n - 1; k >= 0; k--) { if ((k < nrt) & (e[k] != 0)) { // TODO: The following is a pseudo correction to make SVD // work on matrices with n > m (less rows than columns). // For the proper correction, compute the decomposition of the // transpose of A and swap the left and right eigenvectors // Original line: // for (int j = k + 1; j < nu; j++) // Pseudo correction: // for (int j = k + 1; j < n; j++) for (int j = k + 1; j < n; j++) // pseudo-correction { Double t = 0; for (int i = k + 1; i < n; i++) { t += v[i, k] * v[i, j]; } t = -t / v[k + 1, k]; for (int i = k + 1; i < n; i++) { v[i, j] += t * v[i, k]; } } } for (int i = 0; i < n; i++) { v[i, k] = 0; } v[k, k] = 1; } // Main iteration loop for the singular values. int pp = p - 1; int iter = 0; while (p > 0) { int k, kase; // Here is where a test for too many iterations would go. // This section of the program inspects for // negligible elements in the s and e arrays. On // completion the variables kase and k are set as follows. // kase = 1 if s(p) and e[k-1] are negligible and k<p // kase = 2 if s(k) is negligible and k<p // kase = 3 if e[k-1] is negligible, k<p, and // s(k), ..., s(p) are not negligible (qr step). // kase = 4 if e(p-1) is negligible (convergence). for (k = p - 2; k >= -1; k--) { if (k == -1) break; if (System.Math.Abs(e[k]) <= tiny + eps * (System.Math.Abs(s[k]) + System.Math.Abs(s[k + 1]))) { e[k] = 0; break; } } if (k == p - 2) { kase = 4; } else { int ks; for (ks = p - 1; ks >= k; ks--) { if (ks == k) break; Double t = (ks != p ? System.Math.Abs(e[ks]) : 0) + (ks != k + 1 ? System.Math.Abs(e[ks - 1]) : 0); if (System.Math.Abs(s[ks]) <= tiny + eps * t) { s[ks] = 0; break; } } if (ks == k) kase = 3; else if (ks == p - 1) kase = 1; else { kase = 2; k = ks; } } k++; // Perform the task indicated by kase. switch (kase) { // Deflate negligible s(p). case 1: { Double f = e[p - 2]; e[p - 2] = 0; for (int j = p - 2; j >= k; j--) { Double t = Hypotenuse(s[j], f); Double cs = s[j] / t; Double sn = f / t; s[j] = t; if (j != k) { f = -sn * e[j - 1]; e[j - 1] = cs * e[j - 1]; } for (int i = 0; i < n; i++) { t = cs * v[i, j] + sn * v[i, p - 1]; v[i, p - 1] = -sn * v[i, j] + cs * v[i, p - 1]; v[i, j] = t; } } } break; // Split at negligible s(k). case 2: { Double f = e[k - 1]; e[k - 1] = 0; for (int j = k; j < p; j++) { Double t = Hypotenuse(s[j], f); Double cs = s[j] / t; Double sn = f / t; s[j] = t; f = -sn * e[j]; e[j] = cs * e[j]; for (int i = 0; i < m; i++) { t = cs * u[i, j] + sn * u[i, k - 1]; u[i, k - 1] = -sn * u[i, j] + cs * u[i, k - 1]; u[i, j] = t; } } } break; // Perform one qr step. case 3: { // Calculate the shift. Double scale = System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Max(System.Math.Abs(s[p - 1]), System.Math.Abs(s[p - 2])), System.Math.Abs(e[p - 2])), System.Math.Abs(s[k])), System.Math.Abs(e[k])); Double sp = s[p - 1] / scale; Double spm1 = s[p - 2] / scale; Double epm1 = e[p - 2] / scale; Double sk = s[k] / scale; Double ek = e[k] / scale; Double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2; Double c = (sp * epm1) * (sp * epm1); double shift = 0; if ((b != 0) | (c != 0)) { if (b < 0) shift = -System.Math.Sqrt(b * b + c); else shift = System.Math.Sqrt(b * b + c); shift = c / (b + shift); } Double f = (sk + sp) * (sk - sp) + (Double)shift; Double g = sk * ek; // Chase zeros. for (int j = k; j < p - 1; j++) { Double t = Hypotenuse(f, g); Double cs = f / t; Double sn = g / t; if (j != k) e[j - 1] = t; f = cs * s[j] + sn * e[j]; e[j] = cs * e[j] - sn * s[j]; g = sn * s[j + 1]; s[j + 1] = cs * s[j + 1]; for (int i = 0; i < n; i++) { /*t = cs * v[i, j] + sn * v[i, j + 1]; v[i, j + 1] = -sn * v[i, j] + cs * v[i, j + 1]; v[i, j] = t;*/ Double vij = v[i, j]; // *vj; Double vij1 = v[i, j + 1]; // *vj1; t = cs * vij + sn * vij1; v[i, j + 1] = -sn * vij + cs * vij1; v[i, j] = t; } t = Hypotenuse(f, g); cs = f / t; sn = g / t; s[j] = t; f = cs * e[j] + sn * s[j + 1]; s[j + 1] = -sn * e[j] + cs * s[j + 1]; g = sn * e[j + 1]; e[j + 1] = cs * e[j + 1]; if (j < m - 1) { for (int i = 0; i < m; i++) { /* t = cs * u[i, j] + sn * u[i, j + 1]; u[i, j + 1] = -sn * u[i, j] + cs * u[i, j + 1]; u[i, j] = t;*/ Double uij = u[i, j]; // *uj; Double uij1 = u[i, j + 1]; // *uj1; t = cs * uij + sn * uij1; u[i, j + 1] = -sn * uij + cs * uij1; u[i, j] = t; } } } e[p - 2] = f; iter = iter + 1; } break; // Convergence. case 4: { // Make the singular values positive. if (s[k] <= 0) { s[k] = (s[k] < 0 ? -s[k] : 0); for (int i = 0; i <= pp; i++) v[i, k] = -v[i, k]; } // Order the singular values. while (k < pp) { if (s[k] >= s[k + 1]) break; Double t = s[k]; s[k] = s[k + 1]; s[k + 1] = t; int ti = si[k]; si[k] = si[k + 1]; si[k + 1] = ti; if (k < n - 1) { for (int i = 0; i < n; i++) { t = v[i, k + 1]; v[i, k + 1] = v[i, k]; v[i, k] = t; } } if (k < m - 1) { for (int i = 0; i < m; i++) { t = u[i, k + 1]; u[i, k + 1] = u[i, k]; u[i, k] = t; } } k++; } iter = 0; p--; } break; } } }
public double[,] spreadsmatrix(DataTable initdata, double injcharge, double widthcharge) { //Declare ?D-String array //here we start from second row as ColumnNames are stored in first row double[,] initarray = new Double[initdata.Rows.Count, initdata.Columns.Count-1]; double[,] resultarray = new Double[initdata.Columns.Count-1, initdata.Columns.Count - 1]; //Now save DataTable values in array, for (int row = 0; row < initdata.Rows.Count; row++) { for (int col = 1; col < initdata.Columns.Count; col++) { initarray[row, col-1] = Math.Round((double)initdata.Rows[(row)][col], 6); } } //find the discounted spreads for injection in month i and withdraw in month j // Each value shown in the table represents the discounted revenue the owner of the facility would receive by //injecting one unit of gas and withdrawing it at a later time, inclusive of injection costs and withdrawal costs... for (int i = 0; i < resultarray.GetLength(0); i++) { int ij = i; for (int j = initarray.GetLength(1); j > i; j--) { resultarray[i, ij] = Math.Round(((initarray[0, j - 1] + widthcharge) - (initarray[0, i] - injcharge)), 5); ij++; } } return resultarray; }
/// <summary> /// 求解t时刻位于隐藏状态Si的概率矩阵 /// </summary> /// <param name="ALPHA">前向算法局部概率</param> /// <param name="BETA">后向算法局部概率</param> /// <param name="GAMMA">输出:各时刻位于各隐藏状态的概率矩阵</param> private void ComputeGamma(Double[,] ALPHA, Double[,] BETA, ref Double[,] GAMMA) { Int32 T = ALPHA.GetLength(0); if (GAMMA == null) GAMMA = new Double[T, N]; for (Int32 t = 0; t < T; t++) { Double Denominator = 0; for (Int32 i = 0; i < N; i++) { GAMMA[t, i] = ALPHA[t, i] * BETA[t, i]; Denominator += GAMMA[t, i]; } for (Int32 i = 0; i < N; i++) { GAMMA[t, i] /= Denominator; // 保证各时刻的概率总和等于1 } } }
/// <summary> /// Zapisuje macierz danych z pliku. /// </summary> private void SaveFile(String sciezka, Double[,] matrix) { using (StreamWriter stream = new StreamWriter(sciezka)) { for (Int32 i = 0; i < matrix.GetLength(0); ++i) { for (Int32 j = 0; j < matrix.GetLength(1); ++j) { stream.Write(Double.IsInfinity(matrix[i, j]) ? "INF" : matrix[i, j].ToString()); stream.Write("; "); } stream.WriteLine(); } } }
/// <summary> /// Construct an eigenvalue decomposition.</summary> /// /// <param name="value"> /// The matrix to be decomposed.</param> /// <param name="assumeSymmetric"> /// Defines if the matrix should be assumed as being symmetric /// regardless if it is or not. Default is <see langword="false"/>.</param> /// <param name="inPlace"> /// Pass <see langword="true"/> to perform the decomposition in place. The matrix /// <paramref name="value"/> will be destroyed in the process, resulting in less /// memory comsumption.</param> /// <param name="sort"> /// Pass <see langword="true"/> to sort the eigenvalues and eigenvectors at the end /// of the decomposition.</param> /// public EigenvalueDecomposition(Double[,] value, bool assumeSymmetric, bool inPlace = false, bool sort = false) { if (value == null) throw new ArgumentNullException("value", "Matrix cannot be null."); if (value.GetLength(0) != value.GetLength(1)) throw new ArgumentException("Matrix is not a square matrix.", "value"); n = value.GetLength(1); V = new Double[n, n]; d = new Double[n]; e = new Double[n]; this.symmetric = assumeSymmetric; if (this.symmetric) { V = inPlace ? value : (Double[,])value.Clone(); // Tridiagonalize. this.tred2(); // Diagonalize. this.tql2(); } else { H = inPlace ? value : (Double[,])value.Clone(); ort = new Double[n]; // Reduce to Hessenberg form. this.orthes(); // Reduce Hessenberg to real Schur form. this.hqr2(); } if (sort) { // Sort eigenvalues and vectors in descending order var idx = Vector.Range(n); Array.Sort(idx, (i, j) => { if (Math.Abs(d[i]) == Math.Abs(d[j])) return -Math.Abs(e[i]).CompareTo(Math.Abs(e[j])); return -Math.Abs(d[i]).CompareTo(Math.Abs(d[j])); }); this.d = this.d.Get(idx); this.e = this.e.Get(idx); this.V = this.V.Get(null, idx); } }
public static void Map2DNoZ(MappingMode mappingMode, Double[,] array, ImplicitModuleBase module, MappingRanges ranges) { var width = array.GetLength(0); var height = array.GetLength(1); for (var x = 0; x < width; ++x) { for (var y = 0; y < height; ++y) { var p = x / (double)width; var q = y / (double)height; double nx; double ny; double nz; double dx; double dy; var val = 0.00; switch (mappingMode) { case MappingMode.SeamlessNone: nx = ranges.MapX0 + p*(ranges.MapX1 - ranges.MapX0); ny = ranges.MapY0 + q*(ranges.MapY1 - ranges.MapY0); val = module.Get(nx, ny); break; case MappingMode.SeamlessX: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.MapY1 - ranges.MapY0; p = p*(ranges.MapX1 - ranges.MapX0)/(ranges.LoopX1 - ranges.LoopX0); nx = ranges.LoopX0 + Math.Cos(p*PI2)*dx/PI2; ny = ranges.LoopX0 + Math.Sin(p*PI2)*dx/PI2; nz = ranges.MapY0 + q*dy; val = module.Get(nx, ny, nz); break; case MappingMode.SeamlessY: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.LoopY1 - ranges.LoopY0; q = q*(ranges.MapY1 - ranges.MapY0)/(ranges.LoopY1 - ranges.LoopY0); nx = ranges.MapX0 + p*dx; ny = ranges.LoopY0 + Math.Cos(q*PI2)*dy/PI2; nz = ranges.LoopY0 + Math.Sin(q*PI2)*dy/PI2; val = module.Get(nx, ny, nz); break; case MappingMode.SeamlessXY: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.LoopY1 - ranges.LoopY0; p = p*(ranges.MapX1 - ranges.MapX0)/(ranges.LoopX1 - ranges.LoopX0); q = q*(ranges.MapY1 - ranges.MapY0)/(ranges.LoopY1 - ranges.LoopY0); nx = ranges.LoopX0 + Math.Cos(p*PI2)*dx/PI2; ny = ranges.LoopX0 + Math.Sin(p*PI2)*dx/PI2; nz = ranges.LoopY0 + Math.Cos(q*PI2)*dy/PI2; double nw = ranges.LoopY0 + Math.Sin(q*PI2)*dy/PI2; val = module.Get(nx, ny, nz, nw); break; } array[x, y] = val; } } }
static Term[,] array(Double[] m) { int rows = m.GetLength(0); Term[,] r = new Term[rows, 1]; for (int row = 0; row < rows; row++) r[row, 0] = m[row]; return r; }
public static void Map2D(MappingMode mappingMode, Double[,] array, ImplicitModuleBase module, MappingRanges ranges, Double z) { var width = array.GetLength(0); var height = array.GetLength(1); for (var x = 0; x < width; ++x) { for (var y = 0; y < height; ++y) { var p = x / (double)width; var q = y / (double)height; double r; double nx; double ny; double nz; double nw; double nu; double dx; double dy; double dz; var val = 0.00; switch (mappingMode) { case MappingMode.SeamlessNone: nx = ranges.MapX0 + p*(ranges.MapX1 - ranges.MapX0); ny = ranges.MapY0 + q*(ranges.MapY1 - ranges.MapY0); nz = z; val = module.Get(nx, ny, nz); break; case MappingMode.SeamlessX: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.MapY1 - ranges.MapY0; p = p*(ranges.MapX1 - ranges.MapX0)/(ranges.LoopX1 - ranges.LoopX0); nx = ranges.LoopX0 + Math.Cos(p*PI2)*dx/PI2; ny = ranges.LoopX0 + Math.Sin(p*PI2)*dx/PI2; nz = ranges.MapY0 + q*dy; nw = z; val = module.Get(nx, ny, nz, nw); break; case MappingMode.SeamlessY: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.LoopY1 - ranges.LoopY0; q = q*(ranges.MapY1 - ranges.MapY0)/(ranges.LoopY1 - ranges.LoopY0); nx = ranges.MapX0 + p*dx; ny = ranges.LoopY0 + Math.Cos(q*PI2)*dy/PI2; nz = ranges.LoopY0 + Math.Sin(q*PI2)*dy/PI2; nw = z; val = module.Get(nx, ny, nz, nw); break; case MappingMode.SeamlessZ: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.MapY1 - ranges.MapY0; dz = ranges.LoopZ1 - ranges.LoopZ0; nx = ranges.MapX0 + p*dx; ny = ranges.MapY0 + p*dy; r = (z - ranges.MapZ0)/(ranges.MapZ1 - ranges.MapZ0); var zval = r*(ranges.MapZ1 - ranges.MapZ0)/(ranges.LoopZ1 - ranges.LoopZ0); nz = ranges.LoopZ0 + Math.Cos(zval*PI2)*dz/PI2; nw = ranges.LoopZ0 + Math.Sin(zval*PI2)*dz/PI2; val = module.Get(nx, ny, nz, nw); break; case MappingMode.SeamlessXY: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.LoopY1 - ranges.LoopY0; p = p*(ranges.MapX1 - ranges.MapX0)/(ranges.LoopX1 - ranges.LoopX0); q = q*(ranges.MapY1 - ranges.MapY0)/(ranges.LoopY1 - ranges.LoopY0); nx = ranges.LoopX0 + Math.Cos(p*PI2)*dx/PI2; ny = ranges.LoopX0 + Math.Sin(p*PI2)*dx/PI2; nz = ranges.LoopY0 + Math.Cos(q*PI2)*dy/PI2; nw = ranges.LoopY0 + Math.Sin(q*PI2)*dy/PI2; nu = z; val = module.Get(nx, ny, nz, nw, nu, 0); break; case MappingMode.SeamlessXZ: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.MapY1 - ranges.MapY0; dz = ranges.LoopZ1 - ranges.LoopZ0; r = (z - ranges.MapZ0)/(ranges.MapZ1 - ranges.MapZ0); var xzval = r*(ranges.MapX1 - ranges.MapZ0)/(ranges.LoopZ1 - ranges.LoopZ0); p = p*(ranges.MapX1 - ranges.MapX0)/(ranges.LoopX1 - ranges.LoopX0); nx = ranges.LoopX0 + Math.Cos(p*PI2)*dx/PI2; ny = ranges.LoopX0 + Math.Sin(p*PI2)*dx/PI2; nz = ranges.MapY0 + q*dy; nw = ranges.LoopZ0 + Math.Cos(xzval*PI2)*dz/PI2; nu = ranges.LoopZ0 + Math.Sin(xzval*PI2)*dz/PI2; val = module.Get(nx, ny, nz, nw, nu, 0); break; case MappingMode.SeamlessYZ: dx = ranges.MapX1 - ranges.MapX0; dy = ranges.LoopY1 - ranges.LoopY0; dz = ranges.LoopZ1 - ranges.LoopZ0; r = (z - ranges.MapZ0)/(ranges.MapZ1 - ranges.MapZ0); var yzval = r*(ranges.MapZ1 - ranges.MapZ0)/(ranges.LoopZ1 - ranges.LoopZ0); q = q*(ranges.MapY1 - ranges.MapY0)/(ranges.LoopY1 - ranges.LoopY0); nx = ranges.MapX0 + p*dx; ny = ranges.LoopY0 + Math.Cos(q*PI2)*dy/PI2; nz = ranges.LoopY0 + Math.Sin(q*PI2)*dy/PI2; nw = ranges.LoopZ0 + Math.Cos(yzval*PI2)*dz/PI2; nu = ranges.LoopZ0 + Math.Sin(yzval*PI2)*dz/PI2; val = module.Get(nx, ny, nz, nw, nu, 0); break; case MappingMode.SeamlessXYZ: dx = ranges.LoopX1 - ranges.LoopX0; dy = ranges.LoopY1 - ranges.LoopY0; dz = ranges.LoopZ1 - ranges.LoopZ0; p = p*(ranges.MapX1 - ranges.MapX0)/(ranges.LoopX1 - ranges.LoopX0); q = q*(ranges.MapY1 - ranges.MapY0)/(ranges.LoopY1 - ranges.LoopY0); r = (z - ranges.MapZ0)/(ranges.MapZ1 - ranges.MapZ0); var xyzval = r*(ranges.MapZ1 - ranges.MapZ0)/(ranges.LoopZ1 - ranges.LoopZ0); nx = ranges.LoopX0 + Math.Cos(p*PI2)*dx/PI2; ny = ranges.LoopX0 + Math.Sin(p*PI2)*dx/PI2; nz = ranges.LoopY0 + Math.Cos(q*PI2)*dy/PI2; nw = ranges.LoopY0 + Math.Sin(q*PI2)*dy/PI2; nu = ranges.LoopZ0 + Math.Cos(xyzval*PI2)*dz/PI2; double nv = ranges.LoopZ0 + Math.Sin(xyzval*PI2)*dz/PI2; val = module.Get(nx, ny, nz, nw, nu, nv); break; } array[x, y] = val; } } }
/// <summary> /// Construct an eigenvalue decomposition.</summary> /// <param name="value"> /// The matrix to be decomposed.</param> /// <param name="assumeSymmetric"> /// Defines if the matrix should be assumed as being symmetric /// regardless if it is or not. Default is <see langword="false"/>.</param> /// <param name="inPlace"> /// Pass <see langword="true"/> to perform the decomposition in place. The matrix /// <paramref name="value"/> will be destroyed in the process, resulting in less /// memory comsumption.</param> public EigenvalueDecomposition(Double[,] value, bool assumeSymmetric, bool inPlace) { if (value == null) { throw new ArgumentNullException("value", "Matrix cannot be null."); } if (value.GetLength(0) != value.GetLength(1)) { throw new ArgumentException("Matrix is not a square matrix.", "value"); } n = value.GetLength(1); V = new Double[n, n]; d = new Double[n]; e = new Double[n]; this.symmetric = assumeSymmetric; if (this.symmetric) { V = inPlace ? value : (Double[,])value.Clone(); // Tridiagonalize. this.tred2(); // Diagonalize. this.tql2(); } else { H = inPlace ? value : (Double[,])value.Clone(); ort = new Double[n]; // Reduce to Hessenberg form. this.orthes(); // Reduce Hessenberg to real Schur form. this.hqr2(); } }
// Method to set up the recording side of neurorighter private bool NRAcquisitionSetup() { lock (this) { if (!taskRunning) { try { this.Cursor = Cursors.WaitCursor; if (switch_record.Value) { // Create file name if (filenameBase == null) //user hasn't specified a file button_BrowseOutputFile_Click(null, null); //call file selection routine if (filenameBase == null) //this happens if the user pressed cancel for the dialog { MessageBox.Show("An output file must be selected before recording."); //display an error message this.Cursor = Cursors.Default; return true; } // If the user is just doing repeated recordings if (checkbox_repeatRecord.Checked || Properties.Settings.Default.useFidTimeStamp) { DateTime nowDate = DateTime.Now;//Get current time (local to computer); string datePrefix = nowDate.ToString("'-'yyyy'-'MM'-'dd'-'HH'-'mm'-'ss"); filenameBase = originalNameBase + datePrefix; } // Look for old files with same name string[] matchFiles; try { matchFiles = Directory.GetFiles(currentSaveDir, currentSaveFile + "*"); } catch { matchFiles = new string[0]; } if (matchFiles.Length > 0) { DialogResult dr = MessageBox.Show("File " + filenameBase + " exists. Overwrite?", "NeuroRighter Warning", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (dr == DialogResult.No) button_BrowseOutputFile_Click(null, null); //call file selection routine else if (dr == DialogResult.Cancel) { this.Cursor = Cursors.Default; return true; } } // Set file base name + number of channels recordingSettings.SetFID(filenameBase); recordingSettings.SetNumElectrodes(numChannels); } // Find out how many devs and channels/dev we are going to need int numDevices = (numChannels > 32 ? Properties.Settings.Default.AnalogInDevice.Count : 1); numChannelsPerDev = (numChannels < 32 ? numChannels : 32); // Set spike buffer lengths spikeBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.RawSampleFrequency); lfpBufferLength = Convert.ToInt32(Properties.Settings.Default.ADCPollingPeriodSec * Properties.Settings.Default.LFPSampleFrequency); // Create spike aquisition task list spikeTask = new List<Task>(numDevices); Properties.Settings.Default.numSpikeTasks = numDevices; NRAIChannelCollection spikeAqSet = new NRAIChannelCollection(numDevices, numChannelsPerDev); spikeAqSet.SetupSpikeCollection(ref spikeTask); // Check audio and video properties if (Properties.Settings.Default.UseSingleChannelPlayback) spikeOutTask = new Task("spikeOutTask"); //For audio output if (checkBox_video.Checked) //NB: This can't be checked unless video is enabled (no need to check properties) triggerTask = new Task("triggerTask"); // Set MUA sample rate double muaSamplingRate = spikeSamplingRate / MUA_DOWNSAMPLE_FACTOR; //Add LFP channels, if configured if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs) { lfpTask = new Task("lfpTask"); for (int i = 0; i < Properties.Settings.Default.NumChannels; ++i) lfpTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.LFPDevice + "/ai" + i.ToString(), "", AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts); setGain(lfpTask, Properties.Settings.Default.LFPgain); lfpTask.Control(TaskAction.Verify); } //Add EEG channels, if configured if (Properties.Settings.Default.UseEEG) { eegTask = new Task("eegTask"); for (int i = 0; i < Properties.Settings.Default.EEGNumChannels; ++i) eegTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.EEGDevice + "/ai" + (i).ToString(), "", AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts); setGain(eegTask, (double)Properties.Settings.Default.EEGGain); eegTask.Control(TaskAction.Verify); eegSamplingRate = Properties.Settings.Default.EEGSamplingRate; } //Add channel to control Cineplex, if configured if (checkBox_video.Checked) triggerTask.DOChannels.CreateChannel(Properties.Settings.Default.CineplexDevice + "/Port0/line0:7", "", ChannelLineGrouping.OneChannelForAllLines); //Change gain based on comboBox values (1-100) for (int i = 0; i < spikeTask.Count; ++i) setGain(spikeTask[i], Properties.Settings.Default.A2Dgain); //Verify the Tasks for (int i = 0; i < spikeTask.Count; ++i) spikeTask[i].Control(TaskAction.Verify); //if (Properties.Settings.Default.UseSingleChannelPlayback) // spikeOutTask.Control(TaskAction.Verify); //Get sampling rates, set to private variables spikeSamplingRate = Properties.Settings.Default.RawSampleFrequency; lfpSamplingRate = Properties.Settings.Default.LFPSampleFrequency; //Version with videoTask as master clock if (Properties.Settings.Default.UseCineplex) { for (int i = 0; i < spikeTask.Count; ++i) { spikeTask[i].Timing.ReferenceClockSource = videoTask.Timing.ReferenceClockSource; spikeTask[i].Timing.ReferenceClockRate = videoTask.Timing.ReferenceClockRate; } } else { string masterclock = "/" + Properties.Settings.Default.AnalogInDevice[0].ToString() + "/10MhzRefClock";//"OnboardClock";// if (!Properties.Settings.Default.UseStimulator) { //Deal with non M-series devices (these can't use "ReferenceClockSource" Device analogInDevice = DaqSystem.Local.LoadDevice(Properties.Settings.Default.AnalogInDevice[0]); if (analogInDevice.ProductCategory == ProductCategory.MSeriesDaq || analogInDevice.ProductCategory == ProductCategory.XSeriesDaq) spikeTask[0].Timing.ReferenceClockSource = masterclock; //This will be the master clock } else { spikeTask[0].Timing.ReferenceClockSource = masterclock;//stimPulseTask.Timing.ReferenceClockSource; spikeTask[0].Timing.ReferenceClockRate = 10000000.0; //stimPulseTask.Timing.ReferenceClockRate; } for (int i = 1; i < spikeTask.Count; ++i) //Set other analog in tasks to master clock { spikeTask[i].Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource; spikeTask[i].Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate; } } spikeTask[0].Timing.ConfigureSampleClock("", spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2)); for (int i = 1; i < spikeTask.Count; ++i) { //Pipe ai dev0's sample clock to slave devices spikeTask[i].Timing.ConfigureSampleClock("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/SampleClock", spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2)); //Trigger off of ai dev0's trigger spikeTask[i].Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising); // Manually allocate buffer memory //spikeTask[i].Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES; } if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs) { lfpTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource; lfpTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate; lfpTask.Timing.ConfigureSampleClock("", lfpSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.LFPSampleFrequency / 2)); // Manually allocate buffer memory //lfpTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES; } else { Properties.Settings.Default.numLFPTasks = Properties.Settings.Default.numSpikeTasks; } if (Properties.Settings.Default.UseEEG) { eegTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource; eegTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate; eegTask.Timing.ConfigureSampleClock("", eegSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Convert.ToDouble(Properties.Settings.Default.EEGSamplingRate) / 2)); // Manually allocate buffer memory //eegTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES; } if (Properties.Settings.Default.UseCineplex) { if (checkBox_video.Checked) { triggerTask.Timing.ConfigureSampleClock("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/SampleClock", spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, 3); } if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs) { lfpTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising); } if (Properties.Settings.Default.UseEEG) { eegTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising); } } if (Properties.Settings.Default.UseStimulator && Properties.Settings.Default.RecordStimTimes) { try { numStimReads = new List<int>(numDevices); for (int i = 0; i < spikeTask.Count; ++i) numStimReads.Add(0); stimTimeTask = new Task("stimTimeTask"); stimTimeTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.StimInfoDevice + "/ai16", "", AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts); stimTimeTask.AIChannels.CreateVoltageChannel(Properties.Settings.Default.StimInfoDevice + "/ai0", "", AITerminalConfiguration.Nrse, -10.0, 10.0, AIVoltageUnits.Volts); //For triggers // Pipe the spikeTasks sample clock to PFI14 on the stim board DaqSystem.Local.ConnectTerminals(spikeTask[0].Timing.ReferenceClockSource, "/" + Properties.Settings.Default.StimulatorDevice.ToString() + "/PFI0"); if (isNormalRecording) stimTimeTask.Timing.ReferenceClockSource = "/" + Properties.Settings.Default.StimulatorDevice.ToString() + "/PFI0"; else stimTimeTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource; stimTimeTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate; stimTimeTask.Timing.ConfigureSampleClock("", spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2)); stimTimeTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger( "/" + Properties.Settings.Default.AnalogInDevice[0] + "/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising); stimTimeTask.Control(TaskAction.Verify); // stim Timing Channel settings object StringCollection stimTimePhysChan = new StringCollection(); for (int i = 0; i < stimTimeTask.AIChannels.Count; ++i) { stimTimePhysChan.Add(stimTimeTask.AIChannels[i].PhysicalName); } // Write down the indicies corresponding to the portion of this task that will // actually record stimulus infromation instead of aux analog input stimTimeChanSet = new NRAIChannelCollection(stimTimePhysChan); int[] stimTimeChannels = new int[] { 0, 1 }; stimTimeChanSet.SetupNumericalChannelOnly(stimTimeChannels); // Manually allocate buffer memory //stimTimeTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES; Console.WriteLine("NRAcquisitionSetup complete"); } catch (Exception e) { MessageBox.Show(e.Message); } } //Setup scaling coefficients (to convert digital values to voltages) scalingCoeffsSpikes = new List<double[]>(spikeTask.Count); for (int i = 0; i < spikeTask.Count; ++i) scalingCoeffsSpikes.Add(spikeTask[0].AIChannels[0].DeviceScalingCoefficients); if (Properties.Settings.Default.SeparateLFPBoard) scalingCoeffsLFPs = lfpTask.AIChannels[0].DeviceScalingCoefficients; if (Properties.Settings.Default.UseEEG) scalingCoeffsEEG = eegTask.AIChannels[0].DeviceScalingCoefficients; // Setup auxiliary recording tasks if (Properties.Settings.Default.useAuxAnalogInput) { // Set up the aux channel set auxChanSet = new NRAIChannelCollection(Properties.Settings.Default.auxAnalogInChan); if (Properties.Settings.Default.auxAnalogInDev == Properties.Settings.Default.StimInfoDevice && Properties.Settings.Default.RecordStimTimes) { // In this case we are recording both stimulus times and aux analog input times on the same // DAQ, so we need to just make the auxAnInTask reference the stimulus timing task twoAITasksOnSingleBoard = true; auxAnInTask = stimTimeTask; auxChanSet.SetupAuxCollection(ref auxAnInTask); } else { // In this case there is no conflict for AI, so we can create a dedicated task for aux analog input twoAITasksOnSingleBoard = false; auxAnInTask = new Task("AuxiliaryAnalogInput"); auxChanSet.SetupAuxCollection(ref auxAnInTask); auxAnInTask.Timing.ReferenceClockSource = spikeTask[0].Timing.ReferenceClockSource; auxAnInTask.Timing.ReferenceClockRate = spikeTask[0].Timing.ReferenceClockRate; //Pipe ai dev0's sample clock to slave devices auxAnInTask.Timing.ConfigureSampleClock("", spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2)); auxAnInTask.Triggers.StartTrigger.ConfigureDigitalEdgeTrigger("/Dev1/ai/StartTrigger", DigitalEdgeStartTriggerEdge.Rising); // Manually allocate buffer memory // auxAnInTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES; // Create space for the buffer auxAnData = new double[auxChanSet.numericalChannels.Length, spikeBufferLength]; } } if (Properties.Settings.Default.useAuxDigitalInput) { auxDigInTask = new Task("AuxiliaryDigitalInput"); auxDigInTask.DIChannels.CreateChannel(Properties.Settings.Default.auxDigitalInPort, "Auxiliary Digitial In", ChannelLineGrouping.OneChannelForAllLines); auxDigInTask.Timing.ConfigureSampleClock("", spikeSamplingRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(Properties.Settings.Default.RawSampleFrequency / 2)); auxDigInTask.Timing.SampleClockSource = spikeTask[0].Timing.SampleClockTerminal; // Manually allocate buffer memory // auxDigInTask.Stream.Buffer.InputBufferSize = DAQ_BUFFER_SIZE_SAMPLES; } #region Setup_Plotting numSnipsDisplayed = (int)numericUpDown_NumSnipsDisplayed.Value; #region PlotData_Buffers //*********************** //Make PlotData buffers //*********************** int downsample, numRows, numCols; const double spikeplotlength = 0.25; //in seconds switch (Properties.Settings.Default.NumChannels) { case 16: numRows = numCols = 4; downsample = 10; break; case 32: numRows = numCols = 6; downsample = 15; break; case 64: numRows = numCols = 8; downsample = 20; //if this gets really small, LFP data won't plot break; default: numRows = numCols = 4; downsample = 5; break; } //Create plot colormap NRBrainbow = (64).GenerateBrainbow(); NRSnipBrainbow = (64).GenerateSnipBrainbow(); NRUnitBrainbow = (64).GenerateUnitBrainbow(); //Initialize graphs if (spikeGraph != null) { spikeGraph.Dispose(); spikeGraph = null; } spikeGraph = new GridGraph(); int samplesPerPlot = (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * spikeSamplingRate / downsample) * (spikeplotlength / Properties.Settings.Default.ADCPollingPeriodSec)); spikeGraph.setup(numRows, numCols, samplesPerPlot, false, 1 / 4.0, spikeTask[0].AIChannels.All.RangeHigh * 2.0); spikeGraph.setMinMax(0, (float)(samplesPerPlot * numCols) - 1, (float)(spikeTask[0].AIChannels.All.RangeLow * (numRows * 2 - 1)), (float)(spikeTask[0].AIChannels.All.RangeHigh)); spikeGraph.Dock = DockStyle.Fill; spikeGraph.Parent = tabPage_spikes; if (Properties.Settings.Default.UseLFPs) { if (lfpGraph != null) { lfpGraph.Dispose(); lfpGraph = null; } lfpGraph = new RowGraph(); lfpGraph.setup(numChannels, (int)((Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * lfpSamplingRate / downsample) * (5 / Properties.Settings.Default.ADCPollingPeriodSec))), 5.0, spikeTask[0].AIChannels.All.RangeHigh * 2.0); if (Properties.Settings.Default.SeparateLFPBoard) lfpGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * lfpSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1, (float)(lfpTask.AIChannels.All.RangeLow * (numChannels * 2 - 1)), (float)(lfpTask.AIChannels.All.RangeHigh)); else lfpGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * lfpSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1, (float)(spikeTask[0].AIChannels.All.RangeLow * (numChannels * 2 - 1)), (float)(spikeTask[0].AIChannels.All.RangeHigh)); lfpGraph.Dock = DockStyle.Fill; lfpGraph.Parent = tabPage_LFPs; } if (Properties.Settings.Default.ProcessMUA) { if (muaGraph != null) { muaGraph.Dispose(); muaGraph = null; } muaGraph = new RowGraph(); muaGraph.setup(numChannels, (int)((Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * muaSamplingRate / downsample) * (5 / Properties.Settings.Default.ADCPollingPeriodSec))), 5.0, spikeTask[0].AIChannels.All.RangeHigh * 2.0); muaGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * muaSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1, (float)(spikeTask[0].AIChannels.All.RangeLow * (numChannels * 2 - 1)), (float)(spikeTask[0].AIChannels.All.RangeHigh)); muaGraph.Dock = DockStyle.Fill; muaGraph.Parent = tabPage_MUA; muaPlotData = new PlotDataRows(numChannels, downsample, (int)(muaSamplingRate * 5), muaSamplingRate, (float)spikeTask[0].AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec); //muaPlotData.setGain(Properties.Settings.Default.LFPDisplayGain); //muaGraph.setDisplayGain(Properties.Settings.Default.LFPDisplayGain); muaPlotData.dataAcquired += new PlotData.dataAcquiredHandler(muaPlotData_dataAcquired); } if (Properties.Settings.Default.UseEEG) { if (eegGraph != null) { eegGraph.Dispose(); eegGraph = null; } eegGraph = new RowGraph(); eegGraph.setup(Properties.Settings.Default.EEGNumChannels, (int)((Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * eegSamplingRate / downsample) * (5 / Properties.Settings.Default.ADCPollingPeriodSec))), 5.0, eegTask.AIChannels.All.RangeHigh * 2.0); eegGraph.setMinMax(0, 5 * (int)(Math.Ceiling(Properties.Settings.Default.ADCPollingPeriodSec * eegSamplingRate / downsample) / Properties.Settings.Default.ADCPollingPeriodSec) - 1, (float)(eegTask.AIChannels.All.RangeLow * (Properties.Settings.Default.EEGNumChannels * 2 - 1)), (float)(eegTask.AIChannels.All.RangeHigh)); eegGraph.Dock = DockStyle.Fill; eegGraph.Parent = tabPage_EEG; } resetSpkWfm(); //Take care of spike waveform graph double ampdec = (1 / Properties.Settings.Default.PreAmpGain); spikePlotData = new PlotDataGrid(numChannels, downsample, (int)(spikeSamplingRate), spikeSamplingRate, (float)(spikeTask[0].AIChannels.All.RangeHigh * 2.0), numRows, numCols, spikeplotlength, Properties.Settings.Default.ChannelMapping, Properties.Settings.Default.ADCPollingPeriodSec); spikePlotData.dataAcquired += new PlotData.dataAcquiredHandler(spikePlotData_dataAcquired); spikePlotData.setGain(Properties.Settings.Default.SpikeDisplayGain); spikeGraph.setDisplayGain(Properties.Settings.Default.SpikeDisplayGain); if (Properties.Settings.Default.UseLFPs) { if (Properties.Settings.Default.SeparateLFPBoard) lfpPlotData = new PlotDataRows(numChannels, downsample, (int)(lfpSamplingRate * 5), lfpSamplingRate, (float)lfpTask.AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec); else lfpPlotData = new PlotDataRows(numChannels, downsample, (int)(lfpSamplingRate * 5), lfpSamplingRate, (float)spikeTask[0].AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec); lfpPlotData.setGain(Properties.Settings.Default.LFPDisplayGain); lfpGraph.setDisplayGain(Properties.Settings.Default.LFPDisplayGain); lfpPlotData.dataAcquired += new PlotData.dataAcquiredHandler(lfpPlotData_dataAcquired); } waveformPlotData = new EventPlotData(numChannels, spikeDet.NumPre + spikeDet.NumPost + 1, (float)(spikeTask[0].AIChannels.All.RangeHigh * 2F), numRows, numCols, numSnipsDisplayed, Properties.Settings.Default.ChannelMapping); waveformPlotData.setGain(Properties.Settings.Default.SpkWfmDisplayGain); spkWfmGraph.setDisplayGain(Properties.Settings.Default.SpkWfmDisplayGain); waveformPlotData.dataAcquired += new EventPlotData.dataAcquiredHandler(waveformPlotData_dataAcquired); waveformPlotData.start(); #endregion if (Properties.Settings.Default.UseEEG) { eegPlotData = new PlotDataRows(Properties.Settings.Default.EEGNumChannels, downsample, (int)(eegSamplingRate * 5), eegSamplingRate, (float)eegTask.AIChannels.All.RangeHigh * 2F, 0.5, 5, Properties.Settings.Default.ADCPollingPeriodSec); eegPlotData.setGain(Properties.Settings.Default.EEGDisplayGain); eegGraph.setDisplayGain(Properties.Settings.Default.EEGDisplayGain); eegPlotData.dataAcquired += new PlotData.dataAcquiredHandler(eegPlotData_dataAcquired); } if (Properties.Settings.Default.useAuxAnalogInput) { // Remove existing plots for (int i = scatterGraph_AuxAnalogData.Plots.Count-1; i > 0; --i) { scatterGraph_AuxAnalogData.Plots.RemoveAt(i); } // Initialize the aux data scatter graph with a plot for each aux Analog channel for (int i = 0; i < Properties.Settings.Default.auxAnalogInChan.Count-1; ++i) { ScatterPlot p = new ScatterPlot(); scatterGraph_AuxAnalogData.Plots.Add(p); } // Initialize the controller auxInputGraphController = new ScatterGraphController(ref scatterGraph_AuxAnalogData); // Make history selector reflect current limits on input //slide_AnalogDispMaxVoltage.Range = new Range(0.05, 10); //slide_AnalogDispWidth.Range = new Range(2*Properties.Settings.Default.ADCPollingPeriodSec, Properties.Settings.Default.datSrvBufferSizeSec); } #endregion #region Setup_Filters //Setup filters, based on user's input resetSpikeFilter(); if (Properties.Settings.Default.UseLFPs) resetLFPFilter(); resetEEGFilter(); muaFilter = new Filters.MUAFilter( numChannels, spikeSamplingRate, spikeBufferLength, Properties.Settings.Default.MUAHighCutHz, Properties.Settings.Default.MUAFilterOrder, MUA_DOWNSAMPLE_FACTOR, Properties.Settings.Default.ADCPollingPeriodSec); #endregion #region Setup_DataStorage //Initialize data storing matrices // numChannels = Properties.Settings.Default.NumChannels; numSpikeReads = new int[spikeTask.Count]; filtSpikeData = new rawType[numChannels][]; if (Properties.Settings.Default.UseLFPs) { filtLFPData = new rawType[numChannels][]; finalLFPData = new rawType[numChannels][]; for (int i = 0; i < filtSpikeData.GetLength(0); ++i) { if (Properties.Settings.Default.SeparateLFPBoard) filtLFPData[i] = new rawType[lfpBufferLength]; else filtLFPData[i] = new rawType[spikeBufferLength]; } } if (Properties.Settings.Default.ProcessMUA) { muaData = new double[numChannels][]; for (int c = 0; c < numChannels; ++c) muaData[c] = new double[spikeBufferLength / MUA_DOWNSAMPLE_FACTOR]; } if (Properties.Settings.Default.UseEEG) { filtEEGData = new double[Properties.Settings.Default.EEGNumChannels][]; for (int i = 0; i < filtEEGData.GetLength(0); ++i) { filtEEGData[i] = new double[eegBufferLength]; } } for (int i = 0; i < filtSpikeData.GetLength(0); ++i) { filtSpikeData[i] = new rawType[spikeBufferLength]; if (Properties.Settings.Default.UseLFPs) finalLFPData[i] = new rawType[lfpBufferLength]; } if (Properties.Settings.Default.UseStimulator) { stimDataBuffer = new double[STIM_BUFFER_LENGTH]; stimJump = (double)spikeSamplingRate * 0.0001; //num. indices in 100 us of data } stimIndices = new List<StimTick>(5); //if devices refresh rate is reset, need to reset SALPA if (checkBox_SALPA.Checked) resetSALPA(); if (spikeDet != null && isNormalRecording) setSpikeDetector(); if (spikeDet.spikeDetector == null) setSpikeDetector(); #endregion #region Verify Tasks if (Properties.Settings.Default.UseStimulator && Properties.Settings.Default.RecordStimTimes) stimTimeTask.Control(TaskAction.Verify); if (Properties.Settings.Default.UseEEG) eegTask.Control(TaskAction.Verify); if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs) lfpTask.Control(TaskAction.Verify); if (checkBox_video.Checked) triggerTask.Control(TaskAction.Verify); for (int i = 0; i < spikeTask.Count; ++i) spikeTask[i].Control(TaskAction.Verify); if (Properties.Settings.Default.useAuxAnalogInput) auxAnInTask.Control(TaskAction.Verify); if (Properties.Settings.Default.useAuxDigitalInput) auxDigInTask.Control(TaskAction.Verify); #endregion SetupFileWriting(); //Set callbacks for data acq. spikeReader = new List<AnalogMultiChannelReader>(spikeTask.Count); for (int i = 0; i < spikeTask.Count; ++i) { spikeReader.Add(new AnalogMultiChannelReader(spikeTask[i].Stream)); spikeReader[i].SynchronizeCallbacks = true; } //if (Properties.Settings.Default.UseSingleChannelPlayback) // spikeOutWriter = new AnalogSingleChannelWriter(spikeOutTask.Stream); if (checkBox_video.Checked) triggerWriter = new DigitalSingleChannelWriter(triggerTask.Stream); //if (Properties.Settings.Default.UseSingleChannelPlayback) // spikeOutWriter.SynchronizeCallbacks = false; //These don't use UI, so they don't need to be synched spikeCallback = new AsyncCallback(AnalogInCallback_spikes); if (Properties.Settings.Default.UseStimulator && Properties.Settings.Default.RecordStimTimes) { stimTimeReader = new AnalogMultiChannelReader(stimTimeTask.Stream); } if (Properties.Settings.Default.SeparateLFPBoard && Properties.Settings.Default.UseLFPs) { lfpReader = new AnalogUnscaledReader(lfpTask.Stream); lfpReader.SynchronizeCallbacks = true; lfpCallback = new AsyncCallback(AnalogInCallback_LFPs); } if (Properties.Settings.Default.UseEEG) { eegReader = new AnalogUnscaledReader(eegTask.Stream); eegReader.SynchronizeCallbacks = true; eegCallback = new AsyncCallback(AnalogInCallback_EEG); } if (Properties.Settings.Default.useAuxAnalogInput) { auxAnReader = new AnalogMultiChannelReader(auxAnInTask.Stream); auxAnReader.SynchronizeCallbacks = true; auxAnCallback = new AsyncCallback(AnalogInCallback_AuxAn); } if (Properties.Settings.Default.useAuxDigitalInput) { auxDigReader = new DigitalSingleChannelReader(auxDigInTask.Stream); auxDigReader.SynchronizeCallbacks = true; auxDigCallback = new AsyncCallback(AnalogInCallback_AuxDig); } //Setup background workers for data processing bwSpikes = new List<BackgroundWorker>(spikeTask.Count); bwIsRunning = new bool[spikeTask.Count]; for (int i = 0; i < spikeTask.Count; ++i) { bwSpikes.Add(new BackgroundWorker()); bwSpikes[i].DoWork += new DoWorkEventHandler(bwSpikes_DoWork); bwSpikes[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(bwSpikes_RunWorkerCompleted); bwSpikes[i].WorkerSupportsCancellation = true; } //Make persistent buffers for spikeData spikeData = new List<AnalogWaveform<double>[]>(spikeReader.Count); for (int i = 0; i < spikeReader.Count; ++i) { spikeData.Add(new AnalogWaveform<double>[numChannelsPerDev]); for (int j = 0; j < numChannelsPerDev; ++j) spikeData[i][j] = new AnalogWaveform<double>(spikeBufferLength); } //Make channel playback task if (Properties.Settings.Default.UseSingleChannelPlayback) BNCOutput = new ChannelOutput(spikeSamplingRate, 0.1, Properties.Settings.Default.ADCPollingPeriodSec, spikeTask[0], Properties.Settings.Default.SingleChannelPlaybackDevice, 0); } catch (Exception exception) { //Display Errors this.Cursor = Cursors.Default; MessageBox.Show(exception.Message); reset(); } // Set up the DataSrv object. This is an object that publishes a nice large data history // for use in closed loop control and other things if (datSrv != null) datSrv = null; datSrv = new DataSrv( Properties.Settings.Default.datSrvBufferSizeSec, checkBox_SALPA.Checked, SALPA_WIDTH, checkBox_spikesFilter.Checked, spikeDet.spikeDetectionLag ); // Set the number of units if appropriate if (spikeDet.spikeSorter != null) datSrv.SetNumberOfUnits(spikeDet.spikeSorter.totalNumberOfUnits, spikeDet.spikeSorter.unit2Channel); Debugger = new Logger(); Debugger.GrabTimer(spikeTask[0]); //Send debug output to the user's application data folder Debugger.SetPath(Path.Combine(Properties.Settings.Default.neurorighterAppDataPath, "neurorighter-log.txt")); //Tell neuroRighter that the tasks now exist taskRunning = true; } else { Console.WriteLine("NRAcquisitionSetup was called while a task was running, and therefore setup did not execute. Perhaps this should have thrown an error"); } } //update gui at the end // Modify the UI, so user doesn't try running multiple instances of tasks spikeDet.numPreSamples.Enabled = false; spikeDet.numPostSamples.Enabled = false; settingsToolStripMenuItem.Enabled = false; button_Train.Enabled = false; button_SetRecordingStreams.Enabled = false; switch_record.Enabled = false; //processingSettingsToolStripMenuItem.Enabled = false; button_startStimFromFile.Enabled = false; button_startClosedLoopStim.Enabled = false; checkBox_SALPA.Enabled = false; //numericUpDown_NumSnipsDisplayed.Enabled = false; button_startClosedLoopStim.Enabled = false; button_scaleUp.Enabled = true; button_scaleDown.Enabled = true; button_scaleReset.Enabled = true; // Disable spike detector saving while running spikeDet.DisableFileMenu(); Console.WriteLine("NRAcquisitionSetup successfully executed"); this.Cursor = Cursors.Default; return false; }