public void simulate(string method) { xVal[0] = 0; List <double> W_1 = new List <double>(); W_1.Add(W_1_start); List <double> W_2 = new List <double>(); W_2.Add(W_2_start); // Først simulerer vi W'erne helt igennem for (int i = 1; i < horizon * gridpoints; i++) { xVal[i] = (i / gridpoints); W_1.Add(normalDist.Sample()); W_2.Add(normalDist.Sample()); } // konstruerer mu r[0] = r0; tau[0] = tau0; mu[0] = mu0; for (int j = 1; j < horizon * gridpoints; j++) { if (method == "cor") { tau[j] = (a1 * (b1 - tau[j - 1]) * (1 / gridpoints) + sigma1 * 0.5 * W_1[j - 1] + sigma1 * 0.5 * W_2[j - 1]); } else { tau[j] = (a1 * (b1 - tau[j - 1]) * (1 / gridpoints) + sigma1 * W_1[j - 1]); } r[j] = (a2 * (b2 - r[j - 1]) * (1 / gridpoints) + sigma2 * W_2[j - 1]); mu[j] = (0.0005 + Math.Pow(10, (5.728 + 0.038 * j - 10))); // Danicas kvindedødelighed } }
/// <summary> /// Produce a vector of curves where the element at index i is a realization of a simulation at /// simulationDates i. If you require the rates directly use <see cref="GetSimulatedRates(Date[])"/> /// </summary> /// <param name="simulationDates">Dates on which the simulation is run. Must all be greater than the /// anchor date.</param> /// <returns></returns> public ICurve[] GetSimulatedCurves(Date[] simulationDates, Currency curveCcy = null) { if (curveCcy == null) { curveCcy = Currency.ANY; } ICurve[] results = new ICurve[simulationDates.Length]; MathNet.Numerics.Distributions.Normal dist = new MathNet.Numerics.Distributions.Normal(); Date previousDate = anchorDate; double[] previousRates = initialRates.Clone() as double[]; double[] currentRates = new double[initialRates.Length]; // Iterate through the simulation dates for (int simCounter = 0; simCounter < simulationDates.Length; simCounter++) { Date currentDate = simulationDates[simCounter]; double dt = (currentDate - previousDate) / 365.0; double sdt = Math.Sqrt(dt); Date[] curveDates = new Date[initialRates.Length]; // Random realizations to be used in simulation. double eps1 = dist.Sample(); double eps2 = dist.Sample(); double eps3 = dist.Sample(); // Iterate thrrough the dates on the curve for (int i = 0; i < initialRates.Length; i++) { curveDates[i] = simulationDates[simCounter].AddTenor(tenors[i]); if (useRelative) { //TODO: add mean correction. double exponent = components[0, i] * vols[0] * sdt * eps1 + components[1, i] * vols[1] * sdt * eps2 + components[2, i] * vols[2] * sdt * eps3; currentRates[i] = previousRates[i] * Math.Exp(exponent); } else { double change = components[0, i] * vols[0] * sdt * eps1 + components[1, i] * vols[1] * sdt * eps2 + components[2, i] * vols[2] * sdt * eps3; currentRates[i] = previousRates[i] + change; if (floorAtZero) { currentRates[i] = Math.Max(0.0, currentRates[i]); } } } currentRates = currentRates.Multiply(multiplier); results[simCounter] = new DatesAndRates(curveCcy, simulationDates[simCounter], curveDates, currentRates, simulationDates[simCounter].AddMonths(360)); previousRates = currentRates.Clone() as double[]; previousDate = new Date(currentDate); } return(results); }
public Chromosome() { weights_distr_mut = new Normal(0, 8); biases_distr_mut = new Normal(0, 1.5); t_distr_mut = new Normal(0, 3); weights_distr_init = new Normal(0, 8); biases_distr_init = new Normal(2.75, 1.5); t_distr_init = new Normal(0, 3); mut_counter = 0; weights = new float[100]; biases = new float[10]; t_consts = new float[10]; fitness = 0; for (int i = 0; i < 100; i++) { if (i < 10) { t_consts [i] = (float)t_distr_init.Sample(); biases [i] = (float)biases_distr_init.Sample(); } weights [i] = (float)weights_distr_init.Sample(); } }
/// <summary>Initializes one column of a float matrix with normal distributed (Gaussian) noise</summary> /// <param name="matrix">the matrix to initialize</param> /// <param name="mean">the mean of the normal distribution drawn from</param> /// <param name="stddev">the standard deviation of the normal distribution</param> /// <param name="column">the column to be initialized</param> static public void ColumnInitNormal(this Matrix<float> matrix, int column, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = MyMediaLite.Random.GetInstance(); for (int i = 0; i < matrix.dim1; i++) matrix[i, column] = (float) nd.Sample(); }
/// <summary>Initializes a float matrix with normal distributed (Gaussian) noise</summary> /// <param name="matrix">the matrix to initialize</param> /// <param name="mean">the mean of the normal distribution drawn from</param> /// <param name="stddev">the standard deviation of the normal distribution</param> static public void InitNormal(this Matrix<float> matrix, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = MyMediaLite.Random.GetInstance(); for (int i = 0; i < matrix.data.Length; i++) matrix.data[i] = (float) nd.Sample(); }
/// <summary>Initialize a collection of floats with values from a normal distribution</summary> /// <param name="vector">the vector to initialize</param> /// <param name="mean">the mean of the normal distribution</param> /// <param name="stddev">the standard deviation of the normal distribution</param> static public void InitNormal(this IList<float> vector, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = MyMediaLite.Random.GetInstance(); for (int i = 0; i < vector.Count; i++) vector[i] = (float) nd.Sample(); }
/// <summary>Initializes one column of a double matrix with normal distributed (Gaussian) noise</summary> /// <param name="matrix">the matrix to initialize</param> /// <param name="mean">the mean of the normal distribution drawn from</param> /// <param name="stddev">the standard deviation of the normal distribution</param> /// <param name="column">the column to be initialized</param> public static void ColumnInitNormal(this Matrix<double> matrix, int column, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = Util.Random.GetInstance(); for (int i = 0; i < matrix.dim1; i++) matrix[i, column] = nd.Sample(); }
/// <summary>Initializes one row of a float matrix with normal distributed (Gaussian) noise</summary> /// <param name="matrix">the matrix to initialize</param> /// <param name="row">the row to be initialized</param> /// <param name="mean">the mean of the normal distribution drawn from</param> /// <param name="stddev">the standard deviation of the normal distribution</param> static public void RowInitNormal(this Matrix<float> matrix, int row, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = MyMediaLite.Random.GetInstance(); for (int j = 0; j < matrix.dim2; j++) matrix[row, j] = (float) nd.Sample(); }
public override void Initialize(List<Agent> agents) { var appSettings = ConfigurationManager.AppSettings; var activityMean = int.Parse(appSettings["RegularAgentActivityMean"]); var activityStd = int.Parse(appSettings["RegularAgentActivityStd"]); var distribution = new Normal(activityMean, activityStd); var interval = distribution.Sample(); ActivityInterval = (int)interval; var contactsMean = int.Parse(appSettings["RegularAgentContactsMean"]); var contactsStd = int.Parse(appSettings["RegularAgentContactsStd"]); distribution = new Normal(contactsMean, contactsStd); var contactsNumber = 0; while (contactsNumber == 0) { contactsNumber = (int)distribution.Sample(); } var strongConnectionsMean = int.Parse(appSettings["RegularAgentStrongConnectionsMean"]); var strongConnectionsStd = int.Parse(appSettings["RegularAgentStrongConnectionsStd"]); distribution = new Normal(strongConnectionsMean, strongConnectionsStd); var strongConnectionsNumber = (int)distribution.Sample(); var strongConnectionsInterval = 0.75 / strongConnectionsNumber; var strongConnectionsIntervalMin = 0.8 * strongConnectionsInterval; var strongConnectionsIntervalDiff = strongConnectionsInterval - strongConnectionsIntervalMin; var random = new Random(); var total = 1.0; var usedIndices = new List<int>(); for (int i = 0; i < contactsNumber; i++) { var currentAgentIndex = random.Next(agents.Count); if (usedIndices.Contains(currentAgentIndex)) { i--; continue; } usedIndices.Add(currentAgentIndex); var currentAgent = agents.ElementAt(currentAgentIndex); var probability = 0.0; if (i < strongConnectionsNumber) { probability = strongConnectionsIntervalMin + random.NextDouble() * strongConnectionsIntervalDiff; } else { if(i == contactsNumber - 1) { probability = total; } else { probability = 0.2 * total; } } total -= probability; Contacts.Add(currentAgent, probability); } }
/// <summary> /// Initialize a matrix with normal distributed values with mean = 0.0 std = 0.01 /// </summary> /// <param name="ids">Identifiers.</param> /// <param name="M">Matrix to initialize</param> private static void initMatrixNormal(int size, ref double[,] M, int K) { MathNet.Numerics.Distributions.Normal normalDist = new MathNet.Numerics.Distributions.Normal(0.0, 0.01); for (int i = 0; i < size; i++) { for (int j = 0; j < K; j++) { M [i, j] = normalDist.Sample(); } } }
public void Mutate() { mut_counter = 0; for (int i = 0; i < 120; i++) { int chance = Random.Range(0, 120); float w = (float)weights_distr_mut.Sample(); if (w < -16f) { w = -16f; } else if (w > 16f) { w = 16f; } float b = (float)biases_distr_mut.Sample(); if (b < -4f) { b = -4f; } else if (b > 4f) { b = 4f; } float t = (float)t_distr_mut.Sample(); if (t < 0.5f) { t = 0.5f; } else if (t > 2.75f) { t = 2.75f; } if (chance == 42) { mut_counter++; if (i < 100) { weights [i] = w; } else if (i < 110) { t_consts [i - 100] = t; } else { biases [i - 110] = b; } } } }
public static IEnumerable<double> Paths(double S, double sigma, double maturity, double N) { double var = sigma*sigma*maturity; Normal n = new Normal(); for (int i = 0; i < N; i++ ) { double normalsample = n.Sample(); double Sf = S * Math.Exp(-0.5 * var + Math.Sqrt(var) * normalsample); yield return Sf; } }
/// <summary> /// Initialize a matrix with normal distributed values with mean = 0.0 std = 0.01 /// </summary> /// <param name="ids">Identifiers.</param> /// <param name="M">Matrix to initialize</param> private static void initMatrixNormal(IList <int> ids, ref double[,] M, ref Dictionary <int, int> mapper, int K) { MathNet.Numerics.Distributions.Normal normalDist = new MathNet.Numerics.Distributions.Normal(0.0, 0.01); int i = 0; foreach (int id in ids) { for (int j = 0; j < K; j++) { M [i, j] = normalDist.Sample(); mapper [id] = i; } i++; } }
public object NormalDistSample(int mean, int stddev, int size, int nbuckets) { var normal = new Normal(mean, stddev); var data = new double[size]; for (var i = 0; i < data.Length; i++) { data[i] = normal.Sample(); } var histogram = new Histogram(data, nbuckets); var buckets = new List<Bucket>(); for (var i = 0; i < histogram.BucketCount; i++) { buckets.Add(histogram[i]); } return buckets.Select(x=> new {lowerBound = x.LowerBound, upperBound = x.UpperBound, count = x.Count}).ToList(); }
//put the cars to be spawned into a map that tells each spawner node when to spawn some number of cars public void setupSpawnersDistribution() { //for testing int sum = 0; int spawnerNum = GridManagerScript.spawners.Count; //make sure we don't devide by 0 if (spawnerNum > 0) { int toAddToFirst = spawnNumber % spawnerNum; int toDistribute = spawnNumber - toAddToFirst; int carsForEach = toDistribute / spawnerNum; //distribute cars for the first node (with the added remainder) using firstNodeCars int firstNodeCars = carsForEach + toAddToFirst; // non deterministic MathNet.Numerics.Distributions.Normal normalDist = new MathNet.Numerics.Distributions.Normal(rushHour, standartDeviation); //now do the rest foreach (var spawner in GridManagerScript.spawners) { int loopsToAllocate = carsForEach; if (spawner == GridManagerScript.spawners.First()) { loopsToAllocate = firstNodeCars; } Dictionary <double, int> carSpawnerBuckets = new Dictionary <double, int>(); for (int i = 0; i < 24; i++) { for (int c = 0; c < 60; c++) { double t = System.Math.Round(i + c / 100.0, 2); carSpawnerBuckets[t] = 0; } } //allocate new buckets for (int i = 0; i < loopsToAllocate; i++) { double spawnTime = normalDist.Sample();//in hours if (spawnTime < 0) { spawnTime = 24 + spawnTime; } double minutes = (int)( (spawnTime - System.Math.Truncate(spawnTime)) * 60) / 100.0; double hours = System.Math.Truncate(spawnTime); double timeOfDay = System.Math.Round((minutes + hours) % 24, 2); try { carSpawnerBuckets[timeOfDay] += 1; sum += 1; } catch (System.Exception) { Debug.Log(timeOfDay); Debug.Log(carSpawnerBuckets.ContainsKey(timeOfDay)); } } spawner.addSpawnBucket(this, carSpawnerBuckets); } //end for non-deterministic //Deterministic // for (int i = 0; i < 24; i++) // { // for (int c = 0; c < 60; c++) // { // //deterministic // } // } //distribute cars for the other nodes (with no remainder) using carsForEach // bool flagFirst = true; // foreach (var spawner in GridManagerScript.spawners) // { // if (flagFirst)//skip first // { // flagFirst = false; // continue; // } // } } }
/// <summary>Initializes one row of a double matrix with normal distributed (Gaussian) noise</summary> /// <param name="matrix">the matrix to initialize</param> /// <param name="row">the row to be initialized</param> /// <param name="mean">the mean of the normal distribution drawn from</param> /// <param name="stddev">the standard deviation of the normal distribution</param> public static void RowInitNormal(this Matrix<double> matrix, int row, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = Util.Random.GetInstance(); for (int j = 0; j < matrix.dim2; j++) matrix[row, j] = nd.Sample(); }
/// <summary>Initializes a float matrix with normal distributed (Gaussian) noise</summary> /// <param name="matrix">the matrix to initialize</param> /// <param name="mean">the mean of the normal distribution drawn from</param> /// <param name="stddev">the standard deviation of the normal distribution</param> public static void InitNormal(this Matrix<float> matrix, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = Util.Random.GetInstance(); for (int i = 0; i < matrix.dim1; i++) for (int j = 0; j < matrix.dim2; j++) matrix[i, j] = (float) nd.Sample(); }
/// <summary> /// Run example /// </summary> /// <a href="http://en.wikipedia.org/wiki/Normal_distribution">Normal distribution</a> public void Run() { // 1. Initialize the new instance of the Normal distribution class with parameters Mean = 0, StdDev = 1 var normal = new Normal(0, 1); Console.WriteLine(@"1. Initialize the new instance of the Normal distribution class with parameters Mean = {0}, StdDev = {1}", normal.Mean, normal.StdDev); Console.WriteLine(); // 2. Distributuion properties: Console.WriteLine(@"2. {0} distributuion properties:", normal); // Cumulative distribution function Console.WriteLine(@"{0} - Сumulative distribution at location '0.3'", normal.CumulativeDistribution(0.3).ToString(" #0.00000;-#0.00000")); // Probability density Console.WriteLine(@"{0} - Probability density at location '0.3'", normal.Density(0.3).ToString(" #0.00000;-#0.00000")); // Log probability density Console.WriteLine(@"{0} - Log probability density at location '0.3'", normal.DensityLn(0.3).ToString(" #0.00000;-#0.00000")); // Entropy Console.WriteLine(@"{0} - Entropy", normal.Entropy.ToString(" #0.00000;-#0.00000")); // Largest element in the domain Console.WriteLine(@"{0} - Largest element in the domain", normal.Maximum.ToString(" #0.00000;-#0.00000")); // Smallest element in the domain Console.WriteLine(@"{0} - Smallest element in the domain", normal.Minimum.ToString(" #0.00000;-#0.00000")); // Mean Console.WriteLine(@"{0} - Mean", normal.Mean.ToString(" #0.00000;-#0.00000")); // Median Console.WriteLine(@"{0} - Median", normal.Median.ToString(" #0.00000;-#0.00000")); // Mode Console.WriteLine(@"{0} - Mode", normal.Mode.ToString(" #0.00000;-#0.00000")); // Variance Console.WriteLine(@"{0} - Variance", normal.Variance.ToString(" #0.00000;-#0.00000")); // Standard deviation Console.WriteLine(@"{0} - Standard deviation", normal.StdDev.ToString(" #0.00000;-#0.00000")); // Skewness Console.WriteLine(@"{0} - Skewness", normal.Skewness.ToString(" #0.00000;-#0.00000")); Console.WriteLine(); // 3. Generate 10 samples Console.WriteLine(@"3. Generate 10 samples"); for (var i = 0; i < 10; i++) { Console.Write(normal.Sample().ToString("N05") + @" "); } Console.WriteLine(); Console.WriteLine(); // 4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram Console.WriteLine(@"4. Generate 100000 samples of the Normal(0, 1) distribution and display histogram"); var data = new double[100000]; for (var i = 0; i < data.Length; i++) { data[i] = normal.Sample(); } ConsoleHelper.DisplayHistogram(data); Console.WriteLine(); // 5. Generate 100000 samples of the Normal(-10, 0.2) distribution and display histogram Console.WriteLine(@"5. Generate 100000 samples of the Normal(-10, 0.01) distribution and display histogram"); normal.Mean = -10; normal.StdDev = 0.01; for (var i = 0; i < data.Length; i++) { data[i] = normal.Sample(); } ConsoleHelper.DisplayHistogram(data); }
/// <summary>Initialize a collection of doubles with values from a normal distribution</summary> /// <param name="vector">the vector to initialize</param> /// <param name="mean">the mean of the normal distribution</param> /// <param name="stddev">the standard deviation of the normal distribution</param> public static void InitNormal(this IList<double> vector, double mean, double stddev) { var nd = new Normal(mean, stddev); nd.RandomSource = Util.Random.GetInstance(); for (int i = 0; i < vector.Count; i++) vector[i] = nd.Sample(); }
private IEnumerable<DenseVector> LogReturns(Normal normal) { var variances = Variances(); foreach(var variance in variances) { var stdev = Math.Sqrt(variance); var drift = -0.5 * variance; var returns = new DenseVector(N); for (int i = 0; i < N; i++) returns[i] = Math.Exp( normal.Sample() * stdev + drift ); returns /= returns.Average(); yield return returns; } }
public void CanSample() { var n = new Normal(); n.Sample(); }
private static double CalculateNextValue(double timeStep, double currentValue, double drift, double variance, Normal normalDistribution) { return currentValue * Math.Exp(((drift-(0.5*Math.Pow(variance,2)))*timeStep) + variance*Math.Sqrt(timeStep)*normalDistribution.Sample()); }
static void Main(string[] args) { string configFile, dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), netFile, NetworkFile, resFile,destResultFile; string[] path = dir.Split(new string[] { "Launch" }, StringSplitOptions.None); string srcResultFile = path[0] +"Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "result.dat"; configFile = path[0] + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "config.param.txt"; Console.WriteLine("Starting the program to generate the network based on Barbasi Albert Model.."); GlobValues glob = new GlobValues(); try { // Read parameters from param.config file read_parameters(configFile, glob); } catch (Exception e) { Console.WriteLine(e.Message); return; } for (int i = 1; i<= glob.numberOfGraphs; i++) { for (double j = glob.minPower; j <= (glob.maxPower + 0.1); j=j+0.1) { // Creating network file netFile = i+ "_BarbasiNetwork_N"+glob.nodes+ "_powerLaw"+j+"_K"+glob.couplingStrength+".edges"; NetworkFile = path[0] + "Launch" + Path.DirectorySeparatorChar + "output" + Path.DirectorySeparatorChar+netFile ; resFile = i + "_res_N" + glob.nodes + "_powerLaw" + j + "_K" + glob.couplingStrength+".dat"; destResultFile = path[0] + "Launch" + Path.DirectorySeparatorChar + "output" + Path.DirectorySeparatorChar + resFile; try { // upload the network to run the Kuramoto Model pop = Network.LoadFromEdgeFile(NetworkFile); // Run the Kuramoto model here and store the results in the output directory NetworkColorizer colorizer = new NetworkColorizer(); // Distribution of natural frequencies double mean_frequency = 1d; Normal normal = new Normal(mean_frequency, mean_frequency / 5d); sync = new Kuramoto(pop, glob.couplingStrength, glob.couplingProb, colorizer, new Func<Vertex, Vertex[]>(v => { return new Vertex[] { v.RandomNeighbor }; }) ); foreach (Vertex v in pop.Vertices) sync.NaturalFrequencies[v] = normal.Sample(); // foreach (int g in network.ClusterIDs) // pacemaker_mode[g] = false; sync.OnStep += new Kuramoto.StepHandler(recordOrder); Logger.AddMessage(LogEntryType.AppMsg, "Press enter to start synchronization experiment..."); Console.ReadLine(); // Run the simulation sync.Run(); // Write the time series to the resultfile if (srcResultFile != null) sync.WriteTimeSeries(srcResultFile); // Moving results of kuramoto model into output directory System.IO.File.Move(srcResultFile, destResultFile); } catch (Exception e) { Console.WriteLine("Error: " + e); } } } }
public static double RectifierNormal() { Normal m = new Normal(0, Std); return m.Sample(); }
private static AggregationResult RunAggregation(ClusterNetwork net, double bias) { Dictionary <Vertex, double> _attributes = new Dictionary <Vertex, double>(); Dictionary <Vertex, double> _aggregates = new Dictionary <Vertex, double>(); MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(0d, 5d); AggregationResult result = new AggregationResult(); result.Modularity = net.NewmanModularityUndirected; double average = 0d; foreach (Vertex v in net.Vertices) { _attributes[v] = normal.Sample(); _aggregates[v] = _attributes[v]; average += _attributes[v]; } average /= (double)net.VertexCount; double avgEstimate = double.MaxValue; result.FinalVariance = double.MaxValue; result.FinalOffset = 0d; for (int k = 0; k < Properties.Settings.Default.ConsensusRounds; k++) { foreach (Vertex v in net.Vertices.ToArray()) { Vertex w = v.RandomNeighbor; List <Vertex> intraNeighbors = new List <Vertex>(); List <Vertex> interNeighbors = new List <Vertex>(); ClassifyNeighbors(net, v, intraNeighbors, interNeighbors); double r = net.NextRandomDouble(); if (r <= bias && interNeighbors.Count > 0) { w = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count)); } _aggregates[v] = aggregate(_aggregates[v], _aggregates[w]); _aggregates[w] = aggregate(_aggregates[v], _aggregates[w]); } avgEstimate = 0d; foreach (Vertex v in net.Vertices.ToArray()) { avgEstimate += _aggregates[v]; } avgEstimate /= (double)net.VertexCount; result.FinalVariance = 0d; foreach (Vertex v in net.Vertices.ToArray()) { result.FinalVariance += Math.Pow(_aggregates[v] - avgEstimate, 2d); } result.FinalVariance /= (double)net.VertexCount; double intraVar = 0d; foreach (int c in net.ClusterIDs) { double localavg = 0d; double localvar = 0d; foreach (Vertex v in net.GetNodesInCluster(c)) { localavg += _aggregates[v]; } localavg /= net.GetClusterSize(c); foreach (Vertex v in net.GetNodesInCluster(c)) { localvar += Math.Pow(_aggregates[v] - localavg, 2d); } localvar /= net.GetClusterSize(c); intraVar += localvar; } intraVar /= 50d; //Console.WriteLine("i = {0:0000}, Avg = {1:0.000}, Estimate = {2:0.000}, Intra-Var = {3:0.000}, Total Var = {4:0.000}", result.iterations, average, avgEstimate, intraVar, totalVar); } result.FinalOffset = average - avgEstimate; return(result); }
private static AggregationResult RunAggregation(ClusterNetwork net, double bias) { Dictionary<Vertex, double> _attributes = new Dictionary<Vertex, double>(); Dictionary<Vertex, double> _aggregates = new Dictionary<Vertex, double>(); MathNet.Numerics.Distributions.Normal normal = new MathNet.Numerics.Distributions.Normal(0d, 5d); AggregationResult result = new AggregationResult(); result.Modularity = net.NewmanModularityUndirected; double average = 0d; foreach (Vertex v in net.Vertices) { _attributes[v] = normal.Sample(); _aggregates[v] = _attributes[v]; average += _attributes[v]; } average /= (double)net.VertexCount; double avgEstimate = double.MaxValue; result.FinalVariance = double.MaxValue; result.FinalOffset = 0d; for (int k = 0; k < Properties.Settings.Default.ConsensusRounds; k++) { foreach (Vertex v in net.Vertices.ToArray()) { Vertex w = v.RandomNeighbor; List<Vertex> intraNeighbors = new List<Vertex>(); List<Vertex> interNeighbors = new List<Vertex>(); ClassifyNeighbors(net, v, intraNeighbors, interNeighbors); double r = net.NextRandomDouble(); if (r <= bias && interNeighbors.Count > 0) w = interNeighbors.ElementAt(net.NextRandom(interNeighbors.Count)); _aggregates[v] = aggregate(_aggregates[v], _aggregates[w]); _aggregates[w] = aggregate(_aggregates[v], _aggregates[w]); } avgEstimate = 0d; foreach (Vertex v in net.Vertices.ToArray()) avgEstimate += _aggregates[v]; avgEstimate /= (double)net.VertexCount; result.FinalVariance = 0d; foreach (Vertex v in net.Vertices.ToArray()) result.FinalVariance += Math.Pow(_aggregates[v] - avgEstimate, 2d); result.FinalVariance /= (double)net.VertexCount; double intraVar = 0d; foreach (int c in net.ClusterIDs) { double localavg = 0d; double localvar = 0d; foreach (Vertex v in net.GetNodesInCluster(c)) localavg += _aggregates[v]; localavg /= net.GetClusterSize(c); foreach (Vertex v in net.GetNodesInCluster(c)) localvar += Math.Pow(_aggregates[v] - localavg, 2d); localvar /= net.GetClusterSize(c); intraVar += localvar; } intraVar /= 50d; //Console.WriteLine("i = {0:0000}, Avg = {1:0.000}, Estimate = {2:0.000}, Intra-Var = {3:0.000}, Total Var = {4:0.000}", result.iterations, average, avgEstimate, intraVar, totalVar); } result.FinalOffset = average - avgEstimate; return result; }
/// <summary> /// For each (position in inputSpaceRandomPositions): /// 1. Create a new InputCell with input bit = position /// 2. Attach a new ProximalSynapse /// 3. Add the synapse to the synapse update list. /// </summary> /// <remarks> /// Prior to receiving any inputs, the region is initialized by computing a list of /// initial potential synapses for each column. This consists of a random set of inputs /// selected from the input space. Each input is represented by a synapse and assigned /// a random permanence value. The random permanence values are chosen with two /// criteria. First, the values are chosen to be in a small range around connectedPerm /// (the minimum permanence value at which a synapse is considered "connected"). This /// enables potential synapses to become connected (or disconnected) after a small /// number of training iterations. Second, each column has a natural center over the /// input region, and the permanence values have a bias towards this center (they /// have higher values near the center). /// /// The concept of Locality Radius is an additional parameter to control how /// far away synapse connections can be made instead of allowing connections anywhere. /// The reason for this is that in the case of video images I wanted to experiment /// with forcing each Column to only learn on a small section of the total input to /// more effectively learn lines or corners in a small section. /// </remarks> internal void CreateProximalSegments() { // Calculates inputRadius for Columns from localityRadius //var inputRadius = (int)Math.Round ( this.Region.LocalityRadius * this.Region.InputProportionX ); // JS // JS - should there be 2 inputRadiae, for X and Y, to allow for non-square input fields? //(1) var inputRadius = (int) Math.Max( 1, Math.Round(this.Region.LocalityRadius * this.Region.InputProportionX)); //inputRadius = (int)Math.Max ( 1, Math.Round ( this.Region.PercentageInputPerColumn * this.Region.InputSize.Height * this.Region.InputSize.Width ) / 2 ); //var inputRadius = (int)Math.Max ( 1, Math.Round ( this.Region.LocalityRadius * Math.Max ( this.Region.InputProportionX, this.Region.InputProportionY ) ) ); // The coordinates of the input space for the Column // Think of input space like a 'imaginary' square below the column center. int minY, maxY, minX, maxX; //(2) if (this.Region.LocalityRadius > 0) { // Compute values of input square and cut radius on edges minX = Math.Max ( 0, this.CentralPositionInInput.X - inputRadius); maxX = Math.Min(this.Region.InputSize.Width - 1, this.CentralPositionInInput.X + inputRadius); minY = Math.Max ( 0, this.CentralPositionInInput.Y - inputRadius); maxY = Math.Min(this.Region.InputSize.Height - 1, this.CentralPositionInInput.Y + inputRadius); } else { minX = 0; minY = 0; maxX = this.Region.InputSize.Width - 1; maxY = this.Region.InputSize.Height - 1; } // Compute input area // (3) int inputArea = (maxX - minX + 1) * (maxY - minY + 1); // Proximal synapses per Column (input segment) // TODO: give user some control over the number of synapses per segment //var synapsesPerSegment = //debug js // (int) (inputArea * this.Region.PercentageInputPerColumn); // (4) var synapsesPerSegment = Math.Max(1, (int)(inputArea * this.Region.PercentageInputPerColumn)); // JS //synapsesPerSegment = Math.Max ( 1, (int)(inputArea * this.Region.InputProportionX) ); // Updates minimum overlap value, i.e. the minimum number of inputs that must // be active for a column to be considered during the inhibition step. //debug js //this.MinOverlap = // (int) Math.Round(synapsesPerSegment * this.Region.PercentageMinOverlap); // (5) this.MinOverlap = Math.Max(1, (int)Math.Round ( synapsesPerSegment * this.Region.PercentageMinOverlap )); // Create all possible x,y positions for this column input space // (6) var inputPositions = new List<Point>(); for (int y = minY; y <= maxY; y++) { for (int x = minX; x <= maxX; x++) { var inputPosition = new Point(x, y); inputPositions.Add(inputPosition); } } // Random sample of unique input positions (no duplicates). // Tie the random seed to this Column's position for reproducibility int randomSeed = (this.PositionInRegion.Y * this.Region.Size.Width) + this.PositionInRegion.X; // (7) IEnumerable<Point> inputRandomPositions = inputPositions.RandomSample(synapsesPerSegment, randomSeed, false); // Initialize the gaussian normal distribution // The values are chosen to be in a small range around connectedPerm // (the minimum permanence value at which a synapse is considered "connected") var gausianNormalDistribution = new Normal ( Synapse.InitialPermanence, Synapse.PermanenceIncrement ); gausianNormalDistribution.RandomSource = new Random ( randomSeed ); // Create proximal synapses to ramdom positions in input int longerSide = Math.Max(this.Region.InputSize.Width, this.Region.InputSize.Height); foreach (var position in inputRandomPositions) { var newInputCell = new InputCell(this.Region, position.X, position.Y); if (this.Region.FullDefaultSpatialPermanence) { // Create new synapse and add it to segment this.ProximalSegment.CreateSynapse(newInputCell, 1.0f); } else { // Get new value for permanence from distribution double permanence = gausianNormalDistribution.Sample(); // Distance from 'center' of this column to the current position in the input space // JS - replaced with more precise code from Ultrafast //var distanceInputFromColumn = new Point (); //distanceInputFromColumn.X = this.CentralPositionInInput.X - position.X; //distanceInputFromColumn.Y = this.CentralPositionInInput.Y - position.Y; //double distanceToInput = Math.Sqrt ( // (distanceInputFromColumn.X * distanceInputFromColumn.X) + // (distanceInputFromColumn.Y * distanceInputFromColumn.Y) ); double distanceX = this.CentralPositionInInput.X - position.X; double distanceY = this.CentralPositionInInput.Y - position.Y; double distanceToInput = Math.Sqrt ( distanceX * distanceX + distanceY * distanceY ); // Each column has a natural center over the input region, and the // permanence values have a bias towards this center (they have higher values near // the center) int radiusBiasPeak = 2; double radiusBiasStandardDeviation = 2.0; // 0.25; double localityBias = radiusBiasPeak / 2.0 * Math.Exp(Math.Pow(distanceToInput / (longerSide * radiusBiasStandardDeviation), 2) / -2); //StreamWriter file = new StreamWriter ( "localityBias.txt", false ); //for (float longSide = 1f; longSide < 10.0f; longSide += 1f) //{ // file.WriteLine ( "RadiusBiasPeak,distToInput,longerSide,SD,localityBias" ); // for (float distToInput = 0.0f; distToInput < 2.0f; distToInput += 0.1f) // { // localityBias = radiusBiasPeak / 2.0f * // Math.Exp ( Math.Pow ( distToInput / // (longSide * radiusBiasStandardDeviation), 2 ) / -2 ); // file.WriteLine ( String.Format ( "{0:0.00},{1:0.00},{2:0.00},{3:0.00},{4:0.0000000}", radiusBiasPeak, distToInput, longSide, radiusBiasStandardDeviation, localityBias ) ); // } //} //file.Close (); double permanenceBias = Math.Min(1.0f, permanence * localityBias); // Create new synapse and add it to segment this.ProximalSegment.CreateSynapse(newInputCell, permanenceBias); } } }
/// <summary> /// Generates a sample from the log-normal distribution using the <i>Box-Muller</i> algorithm. /// </summary> /// <returns>a sample from the distribution.</returns> public double Sample() { return(Math.Exp(Normal.Sample(_random, _mu, _sigma))); }
static void Main(string[] args) { GlobValues glob = new GlobValues(); string configFile, dir = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), inputPath, outputPath; String[] path = dir.Split(new string[] { "Launch" }, StringSplitOptions.None); inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "input"; configFile = inputPath + Path.DirectorySeparatorChar + "config.param.txt"; // outputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "output"; Console.WriteLine("File is : " + configFile); Console.WriteLine("Starting the program to generate the network based on modularity.."); try { // Read parameters from param.config file read_parameters(configFile, glob); } catch { Console.WriteLine("Usage: mono Demo.exe [nodes] [edges] [clusters] [resultfile]"); return; } // Displays the information Console.WriteLine("Given Parameter values"); Console.WriteLine("\n Nodes: " + glob.nodes + "\n Edges: " + glob.edges + "\n Clusters: " + glob.clusters + "\n Modularity MinValue: " + glob.modularityMinValue + "\n Modularity MaxValue: " + glob.modularityMaxValue); Console.WriteLine(" Number of runs: " + glob.numberOfGraphs + "\n Coupling probability value: "+glob.couplingProb*100); string sourceNetworkFile = inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "network.edges"; string sourceResultFile = inputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + "Launch" + Path.DirectorySeparatorChar + "bin" + Path.DirectorySeparatorChar + "Debug" + Path.DirectorySeparatorChar + "result.dat"; // For loop to make n number of Networks with the given size and modularity ... double modularity = glob.modularityMinValue; while (modularity <= glob.modularityMaxValue) { String outputFile = "Result_M" + modularity; outputPath = path[0] + "Launch" + Path.DirectorySeparatorChar + outputFile; System.IO.Directory.CreateDirectory(outputPath); try { for (int n = 1; n <= glob.numberOfGraphs; n++) { network = new ClusterNetwork(glob.nodes, glob.edges, glob.clusters, modularity, true); // Restricting the modularity value upto 1 decimal place // modularity = Math.Round(network.NewmanModularityUndirected, 1); String memberOutputFile = outputPath + Path.DirectorySeparatorChar + "membership.dat"; System.IO.StreamWriter sw = System.IO.File.CreateText(memberOutputFile); int i = 0; foreach (Vertex v in network.Vertices) { v.Label = (i++).ToString(); sw.WriteLine(network.GetClusterForNode(v).ToString()); } sw.Close(); Network.SaveToEdgeFile(network, "network.edges"); Console.WriteLine("Created network with {0} vertices, {1} edges and modularity {2:0.00}", network.VertexCount, network.EdgeCount, modularity); // To move a file or folder to a new location without renaming it. We rename the files after running the Kuramoto model. string destinationResultFile = outputPath + Path.DirectorySeparatorChar + n + "_res_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".dat"; string destinationNetworkFile = outputPath + Path.DirectorySeparatorChar + n + "_network_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".edges"; System.IO.File.Move(outputPath + Path.DirectorySeparatorChar + "membership.dat", outputPath + Path.DirectorySeparatorChar + n + "_mem_N" + network.VertexCount + "_E" + network.EdgeCount + "_C" + glob.clusters + "_M" + modularity + "_K" + glob.couplingStrength + ".dat"); try { Console.WriteLine("Moving the generated files to output directory.."); System.IO.File.Move(sourceNetworkFile, destinationNetworkFile); } catch (IOException e) { Console.WriteLine(e.Message); } // Run the Kuramoto model here and store the results in the output directory NetworkColorizer colorizer = new NetworkColorizer(); // Distribution of natural frequencies double mean_frequency = 1d; Normal normal = new Normal(mean_frequency, mean_frequency / 5d); sync = new Kuramoto(network, glob.couplingStrength, glob.couplingProb, colorizer, new Func<Vertex, Vertex[]>(v => { return new Vertex[] { v.RandomNeighbor }; }) ); foreach (Vertex v in network.Vertices) sync.NaturalFrequencies[v] = normal.Sample(); foreach (int g in network.ClusterIDs) pacemaker_mode[g] = false; sync.OnStep += new Kuramoto.StepHandler(recordOrder); Logger.AddMessage(LogEntryType.AppMsg, "Press enter to start synchronization experiment..."); Console.ReadLine(); // Run the simulation sync.Run(); // Write the time series to the resultfile if (sourceResultFile != null) sync.WriteTimeSeries(sourceResultFile); // Moving results of kuramoto model into output directory System.IO.File.Move(sourceResultFile, destinationResultFile); } } catch (Exception e) { Console.WriteLine("Error: " + e); } modularity = modularity + 0.1; } // End line of the program Console.WriteLine("Program ended successfully.."); }
/// <summary> /// Generates a sample from the log-normal distribution using the <i>Box-Muller</i> algorithm. /// </summary> /// <param name="rnd">The random number generator to use.</param> /// <param name="mu">The log-scale (μ) of the distribution.</param> /// <param name="sigma">The shape (σ) of the distribution. Range: σ ≥ 0.</param> /// <returns>a sample from the distribution.</returns> public static double Sample(System.Random rnd, double mu, double sigma) { return(Math.Exp(Normal.Sample(rnd, mu, sigma))); }
/// <summary> /// Samples student-t distributed random variables. /// </summary> /// <remarks>The algorithm is method 2 in section 5, chapter 9 /// in L. Devroye's "Non-Uniform Random Variate Generation"</remarks> /// <param name="rnd">The random number generator to use.</param> /// <param name="location">The location (μ) of the distribution.</param> /// <param name="scale">The scale (σ) of the distribution. Range: σ > 0.</param> /// <param name="freedom">The degrees of freedom (ν) for the distribution. Range: ν > 0.</param> /// <returns>a random number from the standard student-t distribution.</returns> static double SampleUnchecked(System.Random rnd, double location, double scale, double freedom) { var gamma = Gamma.SampleUnchecked(rnd, 0.5 * freedom, 0.5); return(Normal.Sample(rnd, location, scale * Math.Sqrt(freedom / gamma))); }
static void Main(string[] args) { try { // The resultfile is given as command line argument //nodes = Int32.Parse(args[0]); //edges = Int32.Parse(args[1]); //clusters = Int32.Parse(args[2]); resultfile = args[3]; } catch { Console.WriteLine("Usage: mono Demo.exe [nodes] [edges] [clusters] [resultfile]"); return; } // Create a network of the given size and modularity ... network = new ClusterNetwork(nodes, edges, clusters, 0.63d, true); System.IO.StreamWriter sw = System.IO.File.CreateText("membership.dat"); int i = 0; foreach (Vertex v in network.Vertices) { v.Label = (i++).ToString(); sw.WriteLine(network.GetClusterForNode(v).ToString()); } sw.Close(); Network.SaveToEdgeFile(network, "network.edges"); Console.WriteLine("Created network with {0} vertices, {1} edges and modularity {2:0.00}", network.VertexCount, network.EdgeCount, network.NewmanModularityUndirected); // Run the real-time visualization NetworkColorizer colorizer = new NetworkColorizer(); //NetworkVisualizer.Start(network, new NETGen.Layouts.FruchtermanReingold.FruchtermanReingoldLayout(15), colorizer); //NetworkVisualizer.Layout.DoLayoutAsync(); // Distribution of natural frequencies double mean_frequency = 1d; Normal normal = new Normal(mean_frequency, mean_frequency/5d); sync = new Kuramoto( network, K, colorizer, new Func<Vertex, Vertex[]>(v => { return new Vertex[] {v.RandomNeighbor}; }) ); foreach(Vertex v in network.Vertices) sync.NaturalFrequencies[v] = normal.Sample(); foreach(int g in network.ClusterIDs) pacemaker_mode[g] = false; sync.OnStep += new Kuramoto.StepHandler(recordOrder); Logger.AddMessage(LogEntryType.AppMsg, "Press enter to start synchronization experiment..."); Console.ReadLine(); // Run the simulation sync.Run(); // Write the time series to the resultfile if(resultfile!=null) sync.WriteTimeSeries(resultfile); }