public static void UpdateBalls(Vector3 center, ILPoints balls, ILOutArray <float> velocity, bool addBalls) { using (ILScope.Enter()) { ILArray <float> position = balls.Positions.Storage; ILArray <float> colors = balls.Colors.Storage; if (addBalls) { // increase number of balls (this is very inefficient!) position[full, r(end + 1, end + 10)] = tosingle(randn(3, 10)); colors[full, r(end + 1, end + 10)] = tosingle(rand(4, 10)); velocity[full, r(end + 1, end + 10)] = tosingle(randn(3, 10)); } ILArray <float> d = array <float>(center.X, center.Y, center.Z); ILArray <float> off = position * 0.1f; ILArray <float> dist = sqrt(sum(position * position)); ILArray <int> where = find(dist < 0.2f); velocity[full, where] = velocity[full, where] + tosingle(rand(3, where.Length)) * 0.2f; dist.a = position - d; off.a = off + dist * -0.02f / sqrt(sum(dist * dist)); velocity.a = velocity * 0.95f - off; balls.Positions.Update(position + velocity * 0.12f); ILArray <float> Zs = abs(position[end, full]); colors[end, full] = Zs / maxall(Zs) * 0.7f + 0.3f; balls.Colors.Update(colors); } }
/// <summary> /// computes normalized magnitudes out of raw samples /// </summary> /// <param name="buffer">sample buffer from naudio</param> /// <param name="buffLen">number of samples</param> /// <param name="fftLen">number of samples for fft </param> /// <param name="MaxValue">[output] index of maximum magnitude value</param> /// <returns>normalized magnitudes (for Y axis)</returns> public static ILRetArray <float> GetMagnitudes(byte[] buffer, int buffLen, int fftLen, ILOutArray <int> MaxValue) { using (ILScope.Enter()) { // how many samples returned from naudio? int newSampleLen = Math.Min(buffLen / 2, fftLen); // create a temporary array for the samples ILArray <float> tmp = zeros <float>(fftLen, 1); // transfer byte[] buffer to temp array for (int s = 0; s < newSampleLen; s++) { tmp.SetValue((short)(buffer[s * 2 + 1] << 8 | buffer[s * 2]), s); } // transform into frequency domain, we use a simple cosine window here ILArray <float> cosWin = sin(pif * counter <float>(0f, 1f, tmp.Length, 1) / (tmp.Length - 1)); //ILArray<float> hamm = (0.54f - 0.46f * cos(2f * pif * counter<float>(0f,1f,ret.Length,1)/ (ret.Length - 1))); // compute the magnitudes, keep relevant part only tmp.a = abs(fft(tmp * cosWin)[r(0, end / 2 + 1)]); // some poor mans high pass filter if (tmp.Length > 20) { tmp["0:20"] = tmp[20]; } // compute max values ILArray <int> maxTmpId = 0; // -> we do want the indices ILArray <float> maxTmp = sort(tmp, Indices: maxTmpId, descending: true); // assign to output parameter MaxValue.a = maxTmpId["0:4"]; // return magnitudes Y values return(tmp.T); } }
// the callback from naudio void waveInStream_DataAvailable(object sender, WaveInEventArgs e) { if (m_shutdown) { return; } using (ILScope.Enter()) { // prepare variables for requesting X values and the index of the maximum value ILArray <int> maxID = 1; // convert the recorded samples in computation module: ILArray <float> Y = Computation.GetMagnitudes(e.Buffer, e.BytesRecorded, m_fftlen, maxID); // update the line shape Line.Update(Y); // update the marker point ILArray <float> markerPoints = ILMath.zeros <float>(2, maxID.S[0]); markerPoints[0, ":"] = ILMath.tosingle(maxID); markerPoints[1, ":"] = Y[maxID]; Marker.Update(markerPoints); // on the first only run we zoom to content if (m_startup) { m_startup = false; ilPanel1.Scene.First <ILPlotCube>().Reset(); } // redraw the scene ilPanel1.Refresh(); } }
/// <summary> /// Computes FFT for the given sampleset. /// </summary> /// <param name="Samples">Sampleset on which to compute a FFT</param> public FFT(List <double> Samples, List <BandFrequencyDefinition> CustomBands = null) { using (ILScope.Enter()) { ILInArray <double> inArr = Samples.ToArray(); ILRetArray <complex> output = ILMath.fft(inArr); rawFFTOutput = output.ToArray(); } ComputeFrequencyPowerSamples(); //FrequencyBands ComputeAbsoluteBandPower(BandFrequencyDefinition.Delta); ComputeAbsoluteBandPower(BandFrequencyDefinition.Theta); ComputeAbsoluteBandPower(BandFrequencyDefinition.Alpha); ComputeAbsoluteBandPower(BandFrequencyDefinition.Beta); ComputeAbsoluteBandPower(BandFrequencyDefinition.Gamma); if (CustomBands != null) { foreach (BandFrequencyDefinition customBand in CustomBands) { ComputeAbsoluteBandPower(customBand); } } }
public static List <Item> fastSort(List <Item> unsorted) { //double [] values = unsorted.ConvertAll<double>(item => item.Value).ToArray(); //// maybe more efficient? safes O(n) run //double[] values = new double[unsorted.Count]; //for (int i = 0; i < values.Length; i++) { // values[i] = unsorted[i].Value; //} using (ILScope.Enter()) { // convert incoming ILArray <double> doubles = zeros(unsorted.Count); double[] doublesArr = doubles.GetArrayForWrite(); for (int i = 0; i < doubles.Length; i++) { doublesArr[i] = unsorted[i].Value; } // do fast sort ILArray <double> indices = empty(); doubles = sort(doubles, Indices: indices); // convert outgoing List <Item> ret = new List <Item>(unsorted.Count); foreach (double i in indices) { ret.Add(unsorted[(int)i]); } return(ret); } }
protected void DoNessesaryMagicForStartUp() { Load += (sender, args) => { using (ILScope.Enter()) { Clock.Running = true; } }; Configure(); }
/// <summary> /// Create some test data for plotting /// </summary> /// <param name="ang">end angle for a spiral</param> /// <param name="resolution">number of points to plot</param> /// <returns>3d data matrix for plotting, points in columns</returns> public static ILRetArray <float> CreateData(int ang, int resolution) { using (ILScope.Enter()) { ILArray <float> A = linspace <float>(0, ang * pi, resolution); ILArray <float> Pos = zeros <float>(3, A.S[1]); Pos["0;:"] = sin(A); Pos["1;:"] = cos(A); Pos["2;:"] = A; return(Pos); } }
public static ILRetCell DBQuery() { using (ILScope.Enter()) { // prepare return cell ILCell ret = cell(size(2, 2)); // todo: fetch data from db and replace below example data ret[0, 0] = "header_1"; ret[1, 0] = "header_2"; ret[0, 1] = rand(100, 200); ret[1, 1] = ones <float>(2, 3000); return(ret); } }
public void Update(ILInArray <double> A) { using (ILScope.Enter(A)) { var plot = ilPanel1.Scene.First <ILLinePlot>(tag: "mylineplot"); if (plot != null) { plot.Update(ILMath.tosingle(A)); plot.Configure(); ilPanel1.Refresh(); } } }
static void Main(string[] args) { using (ILScope.Enter()) { ILCell data = Helper.DBQuery(); // data is: //Cell [2,2] //[0]: <String> header 1 <Double> [100,200] //[1]: <String> header 2 <Single> [2,3000] // store into mat file ILMatFile mat = new ILMatFile(); var key1 = (string)data.GetArray <string>(0, 0); mat.AddArray(data.GetArray <double>(0, 1), key1); // stores rand(100,200) as key: "header1" // proceed with other columns... // write mat file mat.Write("filename"); } }
public static List <Item> makeData(int n) { List <Item> ret = new List <Item>(n); using (ILScope.Enter()) { ILArray <double> A = rand(1, n); double[] values = A.GetArrayForRead(); for (int i = 0; i < n; i++) { ret.Add(new Item() { Value = values[i] }); } } return(ret); }
/// <summary> /// Example update function used for dynamic updates to the plot /// </summary> /// <param name="A">New data, matching the requirements of your plot</param> public void Update(ILInArray <double> A) { using (ILScope.Enter(A)) { // fetch a reference to the plot var plot = ilPanel1.Scene.First <ILLinePlot>(tag: "mylineplot"); if (plot != null) { // make sure, to convert elements to float plot.Update(ILMath.tosingle(A)); // // ... do more manipulations here ... // finished with updates? -> Call Configure() on the changes plot.Configure(); // cause immediate redraw of the scene ilPanel1.Refresh(); } } }
/// <summary> /// This methids creates a system array based on an ILNumerics array. /// </summary> /// <typeparam name="T">The type of the objects stored in the array.</typeparam> /// <param name="A">The ILNumerics array.</param> /// <returns>Returns the newly created system array contain the values of the ILNumerics array.</returns> private static System.Array toSystemMatrix <T>(ILInArray <T> A) { using (ILScope.Enter(A)) { // some error checking (to be improved...) if (object.Equals(A, null)) { throw new ArgumentException("A may not be null"); } if (!A.IsMatrix) { throw new ArgumentException("Matrix expected"); } // create return array System.Array ret = Array.CreateInstance(typeof(T), A.S.ToIntArray().Reverse().ToArray()); // fetch underlying system array T[] workArr = A.GetArrayForRead(); // copy memory block Buffer.BlockCopy(workArr, 0, ret, 0, Marshal.SizeOf(typeof(T)) * A.S.NumberOfElements); return(ret); } }
private void StartBtn_Click(object sender, EventArgs e) { //string f = FunctionSelectionCombo.SelectedItem.ToString(); //if (!String.IsNullOrEmpty(funkcja)&&!funkcja.Equals("Proszę wybrać funkcję do optymalizacji")) //{ // ileCzastek = Convert.ToInt16(ParticleQuantityUpDown.Value); // maxEpochs = Convert.ToInt16(MaxEpochUpDown.Value); // optymalizacja = new PSO(dziedzinyFunkcji[funkcja], ileCzastek, maxEpochs, funkcja); // MessageBox.Show(string.Format("Znalezione minimum to {0} z błędem {1}", PSO.PSOSolution().Item1, PSO.PSOSolution().Item2),"Rezultat optymalizacji",MessageBoxButtons.OK,MessageBoxIcon.Information); // } // else MessageBox.Show("Nie wybrano funkcji do optymalizacji","BŁĄD!",MessageBoxButtons.OK,MessageBoxIcon.Error); // instrukcja do przycisku start List <Populacja> tmp = new PSO(numberIterations, inertiaw, c1, c2, r1r2, linearinertia).PSOALG(population); this.functionButtonSet(false); animace = new Thread(ShowParticleMove); animace.IsBackground = true; animace.Start(tmp); if (thesame == true) { resetB.Enabled = true; } double[] tab = new double[testnumber]; float[] sum = new float[numberIterations]; float[] best = new float[numberIterations]; float[] worst = new float[numberIterations]; float[] bgfworst = new float[numberIterations]; float[] bgfbest = new float[numberIterations]; float[] bgfav = new float[numberIterations]; float[] globalmin = new float[testnumber]; double wynik = 0; double bestresult = 0; double worstresult = 0; double percentsucess = 0; double tmpbest = 0; double tmpworst = 0; for (int i = 0; i < testnumber; ++i) { population = new Populacja(PopulationSize, dim, Funkcje.FunctionName.type); population.SetRangeOfPopulation(Funkcje.FunctionName.type, error); population.GeneratePopulation(dim); population.ObliczPopulFitness(Funkcje.FunctionName.type); //List<Populacja> tmp = new PSO(numberIterations, inertiaw, c1, c2, r1r2, linearinertia).PSOALG(population);//numberIterations, inertiaw tmp.Remove(tmp.Last()); tab[i] = tmp.Min((x => x.NajlepszaFitness)); //tablica wartości wyników-z tego obliczyc % sukcesów wynik += tab[i]; globalmin[i] = (float)tmp.Min((x => x.NajlepszaFitness)); if (Math.Abs(tab[i] - tmp.First().min) < tmp.First().exitError) { percentsucess++; } if (i == 0) { tmpbest = tab[i]; tmpworst = tab[i]; } int popnumber = 0; foreach (Populacja pop in tmp) { float b = 0; float c = 0; bgfav[popnumber] += (float)pop.NajlepszaFitness / testnumber; var scene = new ILScene(); scene.Screen.First <ILLabel>().Visible = false; foreach (Particle item in pop.population) { // MessageBox.Show(a.Length.ToString()+" " +tmp.populationSize.ToString()); b += (float)item.fitnessValue; } c = (b / pop.population.Count) / testnumber; sum[popnumber] += c; if (tab[i] <= tmpbest) { best[popnumber] = b / pop.population.Count; bgfbest[popnumber] = (float)pop.NajlepszaFitness; bestresult = pop.NajlepszaFitness; tmpbest = tab[i]; } if (tab[i] >= tmpworst) { worst[popnumber] = b / pop.population.Count; bgfworst[popnumber] = (float)pop.NajlepszaFitness; worstresult = pop.NajlepszaFitness; tmpworst = tab[i]; } popnumber++; } } frm.richTextBox1.AppendText("Średnie wartości funkci: " + wynik / testnumber + "\n" + "\n"); frm.richTextBox1.AppendText("Najlepsza wartość funkcji: " + bestresult + "\n" + "\n"); frm.richTextBox1.AppendText("Najgorsza wartość funkcji: " + worstresult + "\n" + "\n"); frm.richTextBox1.AppendText("Procent sukcesu: " + percentsucess / testnumber * 100 + "%" + "\n" + "\n"); var scena = new ILScene(); using (ILScope.Enter()) { ILArray <float> AV = sum; ILArray <float> BEST = best; ILArray <float> WORST = worst; ILArray <float> BGFworst = bgfworst; ILArray <float> BGFbest = bgfbest; ILArray <float> BGFav = bgfav; ILArray <float> GLOBAL = globalmin; var plot = scena.Add(new ILPlotCube() { ScreenRect = new RectangleF(0, 0, 1, 0.4f), Children = { new ILLinePlot(AV.T, lineColor:Color.Yellow), new ILLinePlot(BEST.T, lineColor:Color.Blue), new ILLinePlot(WORST.T, lineColor:Color.Red), } }); var plot1 = scena.Add(new ILPlotCube() { ScreenRect = new RectangleF(0, 0.33f, 1, 0.4f), Children = { new ILLinePlot(BGFav.T, lineColor:Color.Yellow), new ILLinePlot(BGFbest.T, lineColor:Color.Blue), new ILLinePlot(BGFworst.T, lineColor:Color.Red), }, }); var plot2 = scena.Add(new ILPlotCube() { ScreenRect = new RectangleF(0, 0.66f, 1, 0.3f), Children = { new ILLinePlot(GLOBAL.T, markerStyle: MarkerStyle.Diamond, lineColor: Color.Black) }, }); var dg2 = plot2.AddDataGroup(); dg2.Add(new ILLinePlot(GLOBAL.T, markerStyle: MarkerStyle.Diamond, lineColor: Color.Red));//,lineColor: Color.Red)); dg2.ScaleModes.YAxisScale = AxisScale.Logarithmic; var axisY2 = plot2.Axes.Add(new ILAxis(dg2) { AxisName = AxisNames.YAxis, Position = new Vector3(1, 0, 0), Label = { Text = "osiągnięte minimum (log)", Color = Color.Red }, Ticks = { DefaultLabel = { Color = Color.Red } } }); frm.ilgraf.Scene = scena; frm.Show(); } }