void Generate()
    {
        Reset();

        if (useRandomSeed)
        {
            seed = System.DateTime.Now.ToLongTimeString();
        }

        RandomWalk rw = new RandomWalk(map, seed, stepRange);

        for (int i = 0; i < steps; i++)
        {
            rw.Step();
        }

        map = rw.ReturnSteps();

        //DiamondSquare ds = new DiamondSquare(map, 5);
        //ds.GenerateHeightMap(dimension-1);
        //float[,] heightMapValues = ds.ReturnHeightMap();

        /* for (int x = 0; x < dimension; x++)
         * {
         *   for (int y = 0; y < dimension; y++)
         *   {
         *       map[x, y].Height = heightMapValues[x, y];
         *   }
         * }*/

        for (int x = 0; x < dimension; x++)
        {
            for (int y = 0; y < dimension; y++)
            {
                map[x, y].DebugDrawConnections();
            }
        }

        //REPLACE: Does not work

        /*List<Node> oneConnectionList = new List<Node>();
         * for (int x = 0; x < dimension; x++)
         * {
         *  for (int y = 0; y < dimension; y++)
         *  {
         *      if (map[x,y].ConnectedNodes.Count == 1)
         *      {
         *          print("found one");
         *          oneConnectionList.Add(map[x, y]);
         *      }
         *  }
         * }
         *
         * Node[] oneConnection = oneConnectionList.ToArray();
         * oneConnection[UnityEngine.Random.Range(0, oneConnection.Length)].SetNodeType= 1;
         * oneConnection[UnityEngine.Random.Range(0, oneConnection.Length)].SetNodeType = 2;*/

        map[UnityEngine.Random.Range(0, dimension), UnityEngine.Random.Range(0, dimension)].SetNodeType = 1;
        map[UnityEngine.Random.Range(0, dimension), UnityEngine.Random.Range(0, dimension)].SetNodeType = 2;
    }
        private async void BtnStart_Click(object sender, RoutedEventArgs e)
        {
            _loop    = true;
            _seed    = 0;
            _counter = 1;
            ColourFiles();
            if (!long.TryParse(MBox.Text, out _m) || !long.TryParse(ABox.Text, out _a) || !long.TryParse(CBox.Text, out _c))
            {
                MessageBox.Show("Wrong input format");
                return;
            }
            long.TryParse(SeedBox.Text, out _seed);
            // if we set seed as 0 it will be given by actual second
            _last = (_seed == 0) ? DateTime.Now.Ticks % _m : _seed;
            RandomWalk randomWalker = new RandomWalk(_myTiles);

            BtnStart.IsEnabled = false;
            BtnStop.IsEnabled  = true;

            while (_loop)
            {
                loopNumber.Content = _counter++.ToString();
                randomWalker.Update(Next());
                await Task.Delay(200);
            }
        }
Exemplo n.º 3
0
        public void CannotStartTwice()
        {
            var walk = new RandomWalk();

            walk.StartAsync().Wait();
            ExceptionAssert.Throws <Exception>(() => { walk.StartAsync().Wait(); });
        }
Exemplo n.º 4
0
 // Use this for initialization
 void Start()
 {
     zombieNav   = GetComponent <ZombieNavMesh>();
     findClosest = GetComponent <FindClosestEnemyScript>();
     randomWalk  = GetComponent <RandomWalk>();
     zombieNav.agent.Warp(gameObject.transform.position);
 }
Exemplo n.º 5
0
 public MetaparticleEffect(int apiVersion, EventHandler handler, ISection section)
     : base(apiVersion, handler, section)
 {
     mParticleParameters   = new ParticleParams(apiVersion, handler, true);
     mRateCurve            = new DataList <FloatValue>(handler);
     mSizeCurve            = new DataList <FloatValue>(handler);
     mPitchCurve           = new DataList <FloatValue>(handler);
     mRollCurve            = new DataList <FloatValue>(handler);
     mHeadingCurve         = new DataList <FloatValue>(handler);
     mRollOffset           = -1000000000.0f;
     mHeadingOffset        = 0f;
     mColorCurve           = new DataList <ColorValue>(handler);
     mColorVary            = new ColorValue(apiVersion, handler);
     mAlphaCurve           = new DataList <FloatValue>(handler);
     mDirectionalForcesSum = new Vector3ValueLE(apiVersion, handler);
     mGlobalForcesSum      = new Vector3ValueLE(apiVersion, handler);
     mRadialForceLocation  = new Vector3ValueLE(apiVersion, handler);
     mWiggles                      = new DataList <Wiggle>(handler);
     mLoopBoxColorCurve            = new DataList <ColorValue>(handler);
     mLoopBoxAlphaCurve            = new DataList <FloatValue>(handler);
     mSurfaces                     = new DataList <Surface>(handler);
     mAltitudeRange                = new Vector2ValueLE(apiVersion, handler, -10000.0f, 10000.0f);
     mRandomWalk1                  = new RandomWalk(apiVersion, handler);
     mRandomWalk2                  = new RandomWalk(apiVersion, handler);
     mRandomWalkPreferredDirection = new Vector3ValueLE(apiVersion, handler);
     mAttractorOrigin              = new Vector3ValueLE(apiVersion, handler);
     mAttractor                    = new Attractor(apiVersion, handler);
     mPathPoints                   = new DataList <PathPoint>(handler);
 }
Exemplo n.º 6
0
 public ParticleEffect(int apiVersion, EventHandler handler, ISection section)
     : base(apiVersion, handler, section)
 {
     mParticleParameters   = new ParticleParams(apiVersion, handler, true);
     mRateCurve            = new DataList <FloatValue>(handler);
     mSizeCurve            = new DataList <FloatValue>(handler);
     mAspectCurve          = new DataList <FloatValue>(handler);
     mRotationCurve        = new DataList <FloatValue>(handler);
     mAlphaCurve           = new DataList <FloatValue>(handler);
     mColorCurve           = new DataList <ColorValue>(handler);
     mColorVary            = new ColorValue(apiVersion, handler);
     mDrawInfo             = new ResourceReference(apiVersion, handler, section);
     mDirectionalForcesSum = new Vector3ValueLE(apiVersion, handler);
     mRadialForceLocation  = new Vector3ValueLE(apiVersion, handler);
     mWiggles           = new DataList <Wiggle>(handler);
     mLoopBoxColorCurve = new DataList <ColorValue>(handler);
     mLoopBoxAlphaCurve = new DataList <FloatValue>(handler);
     mSurfaces          = new DataList <Surface>(handler);
     mAltitudeRange     = new Vector2ValueLE(apiVersion, handler, -10000.0f, 10000.0f);
     mRandomWalk        = new RandomWalk(apiVersion, handler);
     mAttractorOrigin   = new Vector3ValueLE(apiVersion, handler);
     mAttractor         = new Attractor(apiVersion, handler);
     mPathPoints        = new DataList <PathPoint>(handler);
     mVector01          = new Vector3ValueLE(apiVersion, handler);
     mVector3List01     = new DataList <Vector3ValueLE>(handler);
     mVector02          = new Vector3ValueLE(apiVersion, handler);
     mUnknown140        = new Vector2ValueLE(apiVersion, handler);
     mUnknown150        = new Vector2ValueLE(apiVersion, handler);
     mUnknown180        = new Vector3ValueLE(apiVersion, handler);
     mUnknown190        = new Vector2ValueLE(apiVersion, handler);
     mUnknown1A0        = new Vector2ValueLE(apiVersion, handler);
 }
Exemplo n.º 7
0
        internal static float DenormalizeEpsilon(RandomWalk rw, float epsilonNormalized)
        {
            float minRw = rw.Min(), maxRw = rw.Max();
            float l = maxRw - minRw;
            float min = 0.0f, max = l;

            return(epsilonNormalized * (max - min) + min);
        }
        public static float Run(RandomWalk rw, float epsilonNormalized)
        {
            float          epsilon       = InformationContent.DenormalizeEpsilon(rw, epsilonNormalized);
            ChangeSequence sequence      = new ChangeSequence(rw, epsilon);
            var            probabilities = InformationContent.GetProbabilities(sequence);
            float          entropy       = GetEntropy(probabilities);

            return(entropy);
        }
        public void ExpectedValueShouldBeCorrect()
        {
            float[]    diceValues            = new float[] { 1, 2, 3, 4, 5, 6 };
            float      expectedExpectedValue = 3.500f;
            RandomWalk rw            = new RandomWalk(diceValues);
            float      expectedValue = rw.ExpectedValue(NUMBERS_AFTER_COMMA);

            Assert.AreEqual(expectedExpectedValue, expectedValue, DELTA);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Prepares an array with values for calculating an expected value.
 /// </summary>
 /// <param name="rw">Random walk data.</param>
 /// <param name="mean">Average fitness in random walk.</param>
 /// <returns></returns>
 private static float[] GetNumeratorValues(RandomWalk rw, float mean)
 {
     float[] numeratorValues = new float[rw.Size - 1];
     for (int i = 0; i < rw.Size - 1; ++i)
     {
         numeratorValues[i] = (rw[i] - mean) * (rw[i + 1] - mean);
     }
     return(numeratorValues);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Runs the autocorrelation and returns its length (a tau value in literature).
        /// </summary>
        /// <param name="rw">Random walk data.</param>
        /// <returns></returns>
        public static float Run(RandomWalk rw)
        {
            float mean = rw.Average();
            float var  = rw.Variance(DIGITS_AFTER_COMMA);
            float e    = StandardStatisticsUtils.ExpectedValue(GetNumeratorValues(rw, mean), DIGITS_AFTER_COMMA);
            float ro   = e / var;

            return(1.0f / ro);
        }
        public void VarianceShouldBeCorrect()
        {
            float[]    diceValues            = new float[] { 1, 2, 3, 4, 5, 6 };
            float      expectedVarianceValue = 2.91666667f;
            RandomWalk rw       = new RandomWalk(diceValues);
            float      variance = rw.Variance(NUMBERS_AFTER_COMMA);

            Assert.AreEqual(expectedVarianceValue, variance, DELTA);
        }
        public static float Run(RandomWalk rw, float epsilonNormalized)
        {
            float          epsilon  = InformationContent.DenormalizeEpsilon(rw, epsilonNormalized);
            ChangeSequence sequence = new ChangeSequence(rw, epsilon);
            float          mu       = EstimateSlopeNumberIterative(sequence);
            //float mu = EstimateSlopeNumberRecursive(sequence, 0, 0, 0);
            float pic = mu / sequence.Size;

            return(pic);
        }
 public ChangeSequence(RandomWalk rw, float epsilon) : this(epsilon)
 {
     float iFitness, iMinusOneFitness;
     for (int i = 1; i < rw.Size; ++i)
     {
         iFitness         = rw[i];
         iMinusOneFitness = rw[i - 1];
         Add(iFitness, iMinusOneFitness);
     }
 }
Exemplo n.º 15
0
        public async Task CanStartAndStop()
        {
            var walk = new RandomWalk();
            await walk.StartAsync();

            await walk.StopAsync();

            await walk.StartAsync();

            await walk.StopAsync();
        }
Exemplo n.º 16
0
 public void takeTurn()
 {
     foreach (GameObject e in enemies)
     {
         RandomWalk rw = e.GetComponent <RandomWalk>();
         if (rw != null)
         {
             rw.takeTurn();
         }
     }
 }
Exemplo n.º 17
0
 public RandomWalk(int apiVersion, EventHandler handler, RandomWalk basis)
     : base(apiVersion, handler, basis)
 {
     /*mTime = new Vector2ValueLE(apiVersion, handler, basis.mTime);
      * mStrength = new Vector2ValueLE(apiVersion, handler, basis.mStrength);
      * mTurnRange = basis.mTurnRange;
      * mTurnOffset = basis.mTurnOffset;
      * mMix = basis.mMix;
      * mTurnOffsets = new DataList<FloatValue>(handler, basis.mTurnOffsets);
      * mWalkLoopType = basis.mWalkLoopType;/* */
 }
Exemplo n.º 18
0
        public async Task CanStopMultipletimes()
        {
            var walk = new RandomWalk();
            await walk.StartAsync();

            await walk.StopAsync();

            await walk.StopAsync();

            await walk.StartAsync();

            await walk.StopAsync();
        }
Exemplo n.º 19
0
 public static EmptyGrid ProcessMap(EmptyGrid map, RandomWalkSettings settings)
 {
     // Random Generator
     Random.State initialState = Random.state;
     if (settings.useFixedSeed)
     {
         Random.InitState(settings.seed.GetHashCode());
     }
     else
     {
         Random.InitState(Time.time.ToString().GetHashCode());
     }
     map.values   = RandomWalk.TransformBoolToCell(RandomWalk.GetCarvedMap(map.width, map.height, settings), CellType.Floor, CellType.Wall);
     Random.state = initialState;
     return(map);
 }
Exemplo n.º 20
0
 public override IEnumerator Enter(Machine owner, Brain controller)
 {
     mainMachine = owner;
     myBrain = controller;
     Legs myLegs = myBrain.legs;
     separation = new Separation(controller.allObjects);
     separation.Init(myLegs);
     random = new RandomWalk(1f, 1, 20);
     random.Init (myLegs);
     avoidWalls = new BoxAvoidance(controller.boxes, 3);
     avoidWalls.Init (myLegs);
     avoidWalls.setWeight(100);
     myLegs.addSteeringBehaviour(separation);
     myLegs.addSteeringBehaviour(random);
     myLegs.addSteeringBehaviour(avoidWalls);
     yield return null;
 }
Exemplo n.º 21
0
        public void CouldGenerateRandomWalk()
        {
            var sw = new Stopwatch();

            sw.Restart();
            var acc = new SortedMap <int, double>();

            SortedMap <DateTime, double> sm = null;

            for (int i = 0; i < 10000; i++)
            {
                sm = RandomWalk.Generate(DateTime.Today.AddYears(-1), DateTime.Today, TimeSpan.FromDays(1), 0.5, 3.65, 365.0);
                acc.Add(i, sm.Last.Value);
            }
            sw.Stop();
            Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}");

            // NB internalsvisibleto make it so easy to use values instead of Values
            // hopefully not an issue outside tests
            Console.WriteLine($"Average: {acc.Values.Average()}");
            Console.WriteLine($"StDev: {acc.StDev(int.MaxValue, true).Last.Value}");
            Console.WriteLine("Generated number of values: {0}", sm.Count);
            //gen = null;
        }
Exemplo n.º 22
0
 public override void init()
 {
     if(objectRegistry) {
         objectRegistry.RegisterObject(new SensableObject(gameObject, AgentClassification.Sheep));
     }
     seekBehaviour = new Arrive();
     seekBehaviour.Init (this);
     //separation = new Separation();
     //separation.Init (this);
     //cohesion = new Cohesion();
     //cohesion.Init (this);
     //alignment = new Alignment();
     //alignment.Init (this);
     random = new RandomWalk(0.6f, 1, 2);
     random.Init (this);
     // By name
     var go = GameObject.Find("SheepTarget");
     seekBehaviour.setTarget (go);
     this.addSteeringBehaviour(seekBehaviour);
     //this.addSteeringBehaviour(separation);
     //this.addSteeringBehaviour(cohesion);
     //this.addSteeringBehaviour(alignment);
     this.addSteeringBehaviour(random);
 }
            //
            public bool PrepairDSBpositionsInGenome(RadiationSchema rs, DSBs DSBdata)
            {
                bool bParallel = false; // zzz666

                try
                {
                    RandomWalk rw        = new RandomWalk();
                    int        nmonomers = IntactHumanGenome.WholeGenome();
                    rw.LL       = new Location[nmonomers];
                    rw.nmonomer = new int[nmonomers];
                    Random random   = new Random();
                    int    rnucleus = Convert.ToInt32(R / lattice_dim);
                    int    j        = 0;
                    if (!bParallel)
                    {
                        for (int chn = 0; chn < IntactHumanGenome.nObjs; chn++) // zzz666 split these into subtasks
                        {
                            while (true)
                            {
                                rw.LL[j].X = random.Next(0, 2 * rnucleus) - rnucleus; // RW random origin
                                rw.LL[j].Y = random.Next(0, 2 * rnucleus) - rnucleus;
                                rw.LL[j].Z = random.Next(0, 2 * rnucleus) - rnucleus;
                                if (InsideEllipsoid(rw.LL[j]))
                                {
                                    break;
                                }
                            } // zzz666 these RWs don't have loops or domains yet
                            rw.nmonomer[j] = j;
                            j++;
                            for (int i = 0; i < Convert.ToInt32(IntactHumanGenome.NC[chn] / IntactHumanGenome.monomerSize) - 1; i++)
                            {
                                Location l_temp;
                                switch (random.Next(0, 3))
                                {
                                case 0:
                                {
                                    l_temp.X = rw.LL[j - 1].X + (2 * random.Next(0, 2) - 1);
                                    l_temp.Y = rw.LL[j - 1].Y;
                                    l_temp.Z = rw.LL[j - 1].Z;
                                    if (InsideEllipsoid(l_temp))
                                    {
                                        rw.LL[j] = l_temp;
                                    }
                                }
                                break;

                                case 1:
                                {
                                    l_temp.X = rw.LL[j - 1].X;
                                    l_temp.Y = rw.LL[j - 1].Y + (2 * random.Next(0, 2) - 1);
                                    l_temp.Z = rw.LL[j - 1].Z;
                                    if (InsideEllipsoid(l_temp))
                                    {
                                        rw.LL[j] = l_temp;
                                    }
                                }
                                break;

                                case 2:
                                {
                                    l_temp.X = rw.LL[j - 1].X;
                                    l_temp.Y = rw.LL[j - 1].Y;
                                    l_temp.Z = rw.LL[j - 1].Z + (2 * random.Next(0, 2) - 1);
                                    if (InsideEllipsoid(l_temp))
                                    {
                                        rw.LL[j] = l_temp;
                                    }
                                }
                                break;

                                default:
                                    break;
                                }
                                rw.nmonomer[j] = j;
                                j++;
                            }
                        }
                        if (ApplyRad2RWs(rs, rw, DSBdata)) // collect all sets of DSBs and put them into a list
                        {
                            return(true);
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        //foreach (var item in new ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
                        //{
                        //    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
                        //}
                        int coreCount = 0;
                        foreach (var item in new ManagementObjectSearcher("Select * from Win32_Processor").Get())
                        {
                            coreCount += int.Parse(item["NumberOfCores"].ToString());
                        }
                        //Console.WriteLine("Number Of Cores: {0}", coreCount);
                        //Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);
                        int processorCount        = Environment.ProcessorCount;
                        int logicalprocessorCount = 0;
                        foreach (var item in new ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
                        {
                            //Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
                            logicalprocessorCount += int.Parse(item["NumberOfLogicalProcessors"].ToString());
                        }
                        int      nThreads = coreCount; // zzz ? or logicalprocessorCount?
                        Thread[] oThread  = null;
                        for (thread = 0; thread < nThreads; thread++)
                        {
                            Work        w = new Work(thread, nThreads, rs, DSBdata);
                            ThreadStart threadDelegate = new ThreadStart(Work.DoWork);
                            oThread[thread] = new Thread(threadDelegate);
                            oThread[thread].Start();
                        }
                    }
                    return(true);
                    // zzz666 run subtask all the way here, so that every CPU would produce DSBdata for each own RW, which has 46/nCPU  chromosomes; meaure time with and w/o parallelization
                }
                catch { return(false); }
            }
Exemplo n.º 24
0
        /// <summary>
        /// Runs a random walk process on an aggregate networks and outputs the dynamics of the infection size
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet rw [network_file] [output_file] [RWMode=static_first] [aggregationWindow=1] [steps=1000]");
                Console.WriteLine("\t where RWMode can be ... ");
                Console.WriteLine("\t static_first\t Performs a random walk on the aggregate network that considers betweenness preferences computed from the temporal network");
                Console.WriteLine("\t static_second\t ...");
                return;
            }
            string         out_file = args[2];
            RandomWalkMode mode     = RandomWalkMode.StaticFirstOrder;
            int            runs     = 1;
            int            length   = 1000;

            int aggregationWindow = 1;

            if (args.Length >= 4)
            {
                if (args[3] == "static_second")
                {
                    mode = RandomWalkMode.StaticSecondOrder;
                }
                else
                {
                    Console.WriteLine("Unknown walk mode '{0}'", args[3]);
                }
            }
            if (args.Length >= 5)
            {
                aggregationWindow = int.Parse(args[4]);
            }
            if (args.Length >= 6)
            {
                runs = int.Parse(args[5]);
            }
            if (args.Length >= 7)
            {
                length = int.Parse(args[6]);
            }

            if (!CmdlTools.PromptExistingFile(out_file))
            {
                Console.WriteLine("User opted to exit.");
                return;
            }

            Console.Write("Reading temporal network as undirected network...");
            TemporalNetwork temp_net = TemporalNetwork.ReadFromFile(args[1], true);

            Console.WriteLine("done.");

            if (aggregationWindow != 1)
            {
                Console.WriteLine("Applying aggregation window, length = {0}, time steps before = {1}", aggregationWindow, temp_net.Length);
                temp_net.AggregateTime(aggregationWindow);
                Console.WriteLine("done, time steps after = {0}", temp_net.Length);
            }

            Console.Write("Building aggregate network...");
            WeightedNetwork aggregateNet = temp_net.AggregateNetwork;

            Console.WriteLine("done.");

            Console.WriteLine("Starting random walk ...");

            Dictionary <int, double> tvd = new Dictionary <int, double>();
            RandomWalk walk = new RandomWalk(temp_net, mode);

            for (int t = 0; t < length; t++)
            {
                walk.Step();
                tvd[t] = walk.TVD;
                Console.WriteLine("Node = {0}, step = {1}, tvd={2:0.000}", walk.CurrentNode, t, tvd[t]);
            }

            Console.Write("Writing time series of total variation distance ...");
            StringBuilder sb = new StringBuilder();

            foreach (var step in tvd)
            {
                sb.AppendLine(string.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US").NumberFormat, "{0} {1}", step.Key, step.Value));
            }
            System.IO.File.WriteAllText(out_file + ".dat", sb.ToString());
            Console.WriteLine(" done.");
        }
Exemplo n.º 25
0
        public virtual Func <VisitorSegment> ParseSegments(JToken definition, JobType type)
        {
            if (definition == null || !definition.Any())
            {
                throw new Exception("At least one segment is required");
            }

            var segments = new Dictionary <string, KeyValuePair <VisitorSegment, double> >();

            foreach (var kv in (JObject)definition)
            {
                var segment = new VisitorSegment(kv.Key);
                var def     = (JObject)kv.Value;

                segment.DateGenerator.Hour(t => t.AddPeak(0.4, 0.25, 0, pct: true).AddPeak(0.8, 0.1, 2, 0.2, pct: true));
                //SetUserAgent(segment);


                if (type != JobType.Contacts)
                {
                    segment.VisitorVariables.Add(Variables.Random("VisitCount", new PoissonGenerator(3).Truncate(1, 10)));
                    segment.VisitorVariables.Add(Variables.Random("PageViews", new PoissonGenerator(3).Truncate(1, 10)));
                    segment.VisitVariables.Add(Variables.Random("Pause", new NormalGenerator(7, 7).Truncate(0.25)));
                }

                var visitorBehavior = new RandomWalk(_sitecoreRoot);
                segment.Behavior = () => visitorBehavior;

                segments.Add(kv.Key, new KeyValuePair <VisitorSegment, double>(segment, def.Value <double?>("Weight") ?? 1d));

                var copy = def["Copy"];
                if (copy != null)
                {
                    foreach (var name in copy.Values <string>())
                    {
                        segment.Copy(segments[name].Key);
                    }
                }

                var usedFactories = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);

                foreach (var prop in def)
                {
                    if (prop.Key == "Weight" || prop.Key == "Copy")
                    {
                        continue;
                    }

                    try
                    {
                        Factories[prop.Key].UpdateSegment(segment, prop.Value, this);
                        usedFactories.Add(prop.Key);
                    }
                    catch (KeyNotFoundException)
                    {
                        throw new Exception(string.Format("No factory registered for {0}", prop.Key));
                    }
                }

                foreach (var factory in Factories.Where(factory => !usedFactories.Contains(factory.Key)))
                {
                    factory.Value.SetDefaults(segment, this);
                }

                segment.SortVariables();
            }

            return(segments.Values.Weighted());
        }
                public static void DoWork()
                {
                    RandomWalk rw        = new RandomWalk();
                    int        nmonomers = IntactHumanGenome.WholeGenome();

                    rw.LL       = new Location[nmonomers];
                    rw.nmonomer = new int[nmonomers];
                    Random random   = new Random();
                    int    rnucleus = Convert.ToInt32(R / lattice_dim);
                    int    j        = 0;

                    for (int chn = nThread * IntactHumanGenome.nObjs / nThreads; chn < (nThread + 1) * IntactHumanGenome.nObjs / nThreads; chn++)
                    {
                        while (true)
                        {
                            rw.LL[j].X = random.Next(0, 2 * rnucleus) - rnucleus; // RW random origin
                            rw.LL[j].Y = random.Next(0, 2 * rnucleus) - rnucleus;
                            rw.LL[j].Z = random.Next(0, 2 * rnucleus) - rnucleus;
                            if (InsideEllipsoid(rw.LL[j]))
                            {
                                break;
                            }
                        } // zzz666 these RWs don't have loops or domains yet
                        rw.nmonomer[j] = j;
                        j++;
                        for (int i = 0; i < Convert.ToInt32(IntactHumanGenome.NC[chn] / IntactHumanGenome.monomerSize) - 1; i++)
                        {
                            Location l_temp;
                            switch (random.Next(0, 3))
                            {
                            case 0:
                            {
                                l_temp.X = rw.LL[j - 1].X + (2 * random.Next(0, 2) - 1);
                                l_temp.Y = rw.LL[j - 1].Y;
                                l_temp.Z = rw.LL[j - 1].Z;
                                if (InsideEllipsoid(l_temp))
                                {
                                    rw.LL[j] = l_temp;
                                }
                            }
                            break;

                            case 1:
                            {
                                l_temp.X = rw.LL[j - 1].X;
                                l_temp.Y = rw.LL[j - 1].Y + (2 * random.Next(0, 2) - 1);
                                l_temp.Z = rw.LL[j - 1].Z;
                                if (InsideEllipsoid(l_temp))
                                {
                                    rw.LL[j] = l_temp;
                                }
                            }
                            break;

                            case 2:
                            {
                                l_temp.X = rw.LL[j - 1].X;
                                l_temp.Y = rw.LL[j - 1].Y;
                                l_temp.Z = rw.LL[j - 1].Z + (2 * random.Next(0, 2) - 1);
                                if (InsideEllipsoid(l_temp))
                                {
                                    rw.LL[j] = l_temp;
                                }
                            }
                            break;

                            default:
                                break;
                            }
                            rw.nmonomer[j] = j;
                            j++;
                        }
                    }
                    ApplyRad2RWs(rs, rw, DSBdata); // collect all sets of DSBs and put them into a list
                }
Exemplo n.º 27
0
 private IList<int> GetDefaultSample(int n)
 {
     var walk = new RandomWalk<int, double>(values, probs);
     return walk.GetSample(n); 
 }
            //
            public static bool ApplyRad2RWs(RadiationSchema rs, RandomWalk rw, DSBs DSBdata)
            {
                int ndsb = 0;

                try
                {
                    double dose;
                    double dose_total = 0.0;
                    for (int nb = 0; nb < rs.nBeams; nb++) // iterate over all beams
                    {
                        foreach (int j in rw.nmonomer)
                        {
                            dose        = Dconst;
                            dose_total += Dconst;
                            try
                            {
                                for (int i = 0; i < amorphous_partile_tracks[nb].track_struct.ntracks; i++)
                                {
                                    int x     = amorphous_partile_tracks[nb].track_struct.X[i];
                                    int y     = amorphous_partile_tracks[nb].track_struct.Y[i];
                                    int dist2 = (x - rw.LL[j].X) * (x - rw.LL[j].X) + (y - rw.LL[j].Y) * (y - rw.LL[j].Y);
                                    if (dist2 < Convert.ToInt32((RadiationSchema.Pr / lattice_dim) * (RadiationSchema.Pr / lattice_dim)))
                                    {
                                        int t = Convert.ToInt32(MainForm.Particle.Tracks.grid * lattice_dim * Math.Sqrt(dist2) / RadiationSchema.Pr); // microns
                                        dose       += amorphous_partile_tracks[nb].track_struct.dose[t];
                                        dose_total += amorphous_partile_tracks[nb].track_struct.dose[t];
                                    }
                                }
                            }
                            catch { return(false); }
                            double Q = 0.812 * 35.0 / 25.0; // multiply by 35./25. for high/low LET; also 1e-5 is factored out
                            if (amorphous_partile_tracks[nb].p_t == MainForm.Radiation.p_type.photon)
                            {
                                Q = 0.812; // multiply by 35./25. for high LET
                            }
                            else
                            {
                                Q = 0.812 * 35.0 / 25.0; // multiply by 35./25. for high LET
                            }
                            Q *= 1.0e-5;                 // Q is determined from PFGE experiments
                            Random random = new Random();
                            try
                            {
                                if (SimpleRNG.GetUniform() < 1.0 - Math.Exp(-Q * dose))
                                {
                                    ndsb++;
                                    DSBs.DSBstruct new_dsb = new DSBs.DSBstruct
                                    {
                                        ndsb       = ndsb,
                                        L          = rw.LL[j],
                                        position   = rw.nmonomer[j],
                                        entry_time = rs.entryTime[nb],
                                        exit_time  = rs.exitTime[nb]
                                    };
                                    new_dsb.random_time = SimpleRNG.GetUniform() * (new_dsb.exit_time - new_dsb.entry_time) + new_dsb.entry_time; // a DSB is created sometime during the fractionation interval
                                    double r = SimpleRNG.GetUniform();
                                    if (r < DSBs.DSBcomplP[0])
                                    {
                                        new_dsb.DSBcmplx = DSBs.DSBstruct.DSBcomplexity.simpleDSB;
                                    }
                                    else
                                    {
                                        if (r >= DSBs.DSBcomplP[0] && r < DSBs.DSBcomplP[1]) // zzz can a DSB appear more than 1 time at the same monomer
                                        {
                                            new_dsb.DSBcmplx = DSBs.DSBstruct.DSBcomplexity.DSBplus;
                                        }
                                        else
                                        {
                                            new_dsb.DSBcmplx = DSBs.DSBstruct.DSBcomplexity.DSBplusplus;
                                        }
                                    }
                                    DSBdata.listDSBs.Add(new_dsb);
                                }
                            }
                            catch { return(false); }
                        }
                    }
                    dose_total /= Convert.ToDouble(rw.nmonomer.Length); // total dose integrated over all monomers // zzz might wanna output somewhere
                    return(true);
                }
                catch { return(false); }
            }
Exemplo n.º 29
0
        protected override void Parse(Stream stream)
        {
            var s = new BinaryStreamWrapper(stream, ByteOrder.BigEndian);

            s.Read(out mFlags);
            // no flag mask

            mParticleParameters = new ParticleParams(requestedApiVersion, handler, true, stream);
            mRateCurve          = new DataList <FloatValue>(handler, stream);
            s.Read(out mRateCurveTime);
            s.Read(out mRateCurveCycles);
            mSizeCurve = new DataList <FloatValue>(handler, stream);
            s.Read(out mSizeVary);
            mPitchCurve   = new DataList <FloatValue>(handler, stream);
            mRollCurve    = new DataList <FloatValue>(handler, stream);
            mHeadingCurve = new DataList <FloatValue>(handler, stream);
            s.Read(out mPitchVary);
            s.Read(out mRollVary);
            s.Read(out mHeadingVary);
            s.Read(out mPitchOffset);
            s.Read(out mRollOffset);
            s.Read(out mHeadingOffset);
            mColorCurve = new DataList <ColorValue>(handler, stream);
            mColorVary  = new ColorValue(requestedApiVersion, handler, stream);
            mAlphaCurve = new DataList <FloatValue>(handler, stream);
            s.Read(out mAlphaVary);
            s.Read(out mComponentName, StringType.ZeroDelimited);
            s.Read(out mComponentType, StringType.ZeroDelimited);
            s.Read(out mAlignMode);
            mDirectionalForcesSum = new Vector3ValueLE(requestedApiVersion, handler, stream);
            mGlobalForcesSum      = new Vector3ValueLE(requestedApiVersion, handler, stream);

            s.Read(out mWindStrength);
            s.Read(out mGravityStrength);
            s.Read(out mRadialForce);

            mRadialForceLocation = new Vector3ValueLE(requestedApiVersion, handler, stream);

            s.Read(out mDrag);
            s.Read(out mScrewRate);
            mWiggles = new DataList <Wiggle>(handler, stream);
            s.Read(out mScreenBloomAlphaRate);
            s.Read(out mScreenBloomAlphaBase);
            s.Read(out mScreenBloomSizeRate);
            s.Read(out mScreenBloomSizeBase);
            mLoopBoxColorCurve = new DataList <ColorValue>(handler, stream);
            mLoopBoxAlphaCurve = new DataList <FloatValue>(handler, stream);
            mSurfaces          = new DataList <Surface>(handler, stream);
            s.Read(out mMapBounce);
            s.Read(out mMapRepulseHeight);
            s.Read(out mMapRepulseStrength);
            s.Read(out mMapRepulseScoutDistance);
            s.Read(out mMapRepulseVertical);
            s.Read(out mMapRepulseKillHeight);
            s.Read(out mProbabilityDeath);

            mAltitudeRange = new Vector2ValueLE(requestedApiVersion, handler, stream);

            s.Read(out mForceMapId);
            s.Read(out mEmitRateMapId);
            s.Read(out mEmitColorMapId);

            mRandomWalk1 = new RandomWalk(0, handler, stream);
            mRandomWalk2 = new RandomWalk(0, handler, stream);

            mRandomWalkPreferredDirection = new Vector3ValueLE(requestedApiVersion, handler, stream);

            s.Read(out mAlignDamping);
            s.Read(out mBankAmount);
            s.Read(out mBankRestore);

            mAttractorOrigin = new Vector3ValueLE(requestedApiVersion, handler, stream);
            mAttractor       = new Attractor(requestedApiVersion, handler, stream);

            mPathPoints = new DataList <PathPoint>(handler, stream);
            s.Read(out mTractorResetSpeed);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Runs a random walk process on an aggregate networks and outputs the dynamics of the infection size
        /// </summary>
        /// <param name="args"></param>
        public static void Run(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: TempNet rw [network_file] [output_file] [WalkType=random] [aggregationWindow=1] [runs=1] [length=100000]");
                Console.WriteLine("\t where WalkType can be ... ");
                Console.WriteLine("\t bwp_pres\t Performs a random walk on the aggregate network that considers betweenness preferences computed from the temporal network");
                Console.WriteLine("\t bwp_null\t ...");
                return;
            }
            string out_file = args[2];
            string type     = "bwp_pres";
            int    runs     = 1;
            int    length   = 100000;

            int aggregationWindow = 1;

            if (args.Length >= 4)
            {
                type = args[3];
            }
            if (args.Length >= 5)
            {
                aggregationWindow = int.Parse(args[4]);
            }
            if (args.Length >= 6)
            {
                runs = int.Parse(args[5]);
            }
            if (args.Length >= 7)
            {
                length = int.Parse(args[6]);
            }

            if (!CmdlTools.PromptExistingFile(out_file))
            {
                Console.WriteLine("User opted to exit.");
                return;
            }

            Console.Write("Reading temporal network as undirected network...");
            TemporalNetwork temp_net = TemporalNetwork.ReadFromFile(args[1], true);

            Console.WriteLine("done.");

            if (aggregationWindow != 1)
            {
                Console.WriteLine("Applying aggregation window, length = {0}, time steps before = {1}", aggregationWindow, temp_net.Length);
                temp_net.AggregateTime(aggregationWindow);
                Console.WriteLine("done, time steps after = {0}", temp_net.Length);
            }

            Console.Write("Building aggregate network...");
            WeightedNetwork aggregateNet = temp_net.AggregateNetwork;

            Console.WriteLine("done.");

            for (int r = 2000; r <= 2000 + runs; r++)
            {
                Console.WriteLine("Running Random walk [{0}] in mode [{1}] ...", r, type);
                IDictionary <int, double> tvd = null;
                if (type == "bwp_pres")
                {
                    tvd = RandomWalk.RunRW_BWP(temp_net, length, null_model: false);
                }
                else if (type == "bwp_null")
                {
                    tvd = RandomWalk.RunRW_BWP(temp_net, length, null_model: true);
                }
                else
                {
                    Console.WriteLine("\nError: RWType {0} unknown", type);
                    return;
                }

                Console.Write("Writing time series of total variation distance ...");
                StringBuilder sb = new StringBuilder();
                foreach (var step in tvd)
                {
                    sb.AppendLine(string.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US").NumberFormat, "{0} {1}", step.Key, step.Value));
                }
                System.IO.File.WriteAllText(out_file + "_r_" + r + ".dat", sb.ToString());
                Console.WriteLine(" done.");
            }
        }
Exemplo n.º 31
0
        protected override void Parse(Stream stream)
        {
            var s = new BinaryStreamWrapper(stream, ByteOrder.BigEndian);

            s.Read(out mFlags);
            // no flag mask

            ParticleParameters = new ParticleParams(requestedApiVersion, handler, true, stream);
            mRateCurve         = new DataList <FloatValue>(handler, stream);
            s.Read(out mRateCurveTime);
            s.Read(out mRateCurveCycles);
            s.Read(out mRateSpeedScale);
            mSizeCurve = new DataList <FloatValue>(handler, stream);
            s.Read(out mSizeVary);
            mAspectCurve = new DataList <FloatValue>(handler, stream);
            s.Read(out mAspectVary);
            s.Read(out mRotationVary);
            s.Read(out mRotationOffset);
            mRotationCurve = new DataList <FloatValue>(handler, stream);
            mAlphaCurve    = new DataList <FloatValue>(handler, stream);
            s.Read(out mAlphaVary);
            mColorCurve = new DataList <ColorValue>(handler, stream);
            mColorVary  = new ColorValue(requestedApiVersion, handler, stream);
            mDrawInfo   = new ResourceReference(0, handler, mSection, stream);

            s.Read(out mPhysicsType);
            s.Read(out mOverrideSet);
            s.Read(out mTileCountU);
            s.Read(out mTileCountV);
            s.Read(out mAlignMode);
            s.Read(out mFrameSpeed);
            s.Read(out mFrameStart);
            s.Read(out mFrameCount);
            s.Read(out mFrameRandom);

            mDirectionalForcesSum = new Vector3ValueLE(requestedApiVersion, handler, stream);

            s.Read(out mWindStrength);
            s.Read(out mGravityStrength);
            s.Read(out mRadialForce);

            mRadialForceLocation = new Vector3ValueLE(requestedApiVersion, handler, stream);

            s.Read(out mDrag);
            s.Read(out mVelocityStretch);
            s.Read(out mScrewRate);

            mWiggles = new DataList <Wiggle>(handler, stream);
            s.Read(out mScreenBloomAlphaRate);
            s.Read(out mScreenBloomAlphaBase);
            s.Read(out mScreenBloomSizeRate);
            s.Read(out mScreenBloomSizeBase);
            mLoopBoxColorCurve = new DataList <ColorValue>(handler, stream);
            mLoopBoxAlphaCurve = new DataList <FloatValue>(handler, stream);
            mSurfaces          = new DataList <Surface>(handler, stream);
            s.Read(out mMapBounce);
            s.Read(out mMapRepulseHeight);
            s.Read(out mMapRepulseStrength);
            s.Read(out mMapRepulseScoutDistance);
            s.Read(out mMapRepulseVertical);

            s.Read(out mMapRepulseKillHeight);                                         //-1000000000.0f
            s.Read(out mProbabilityDeath);                                             //0f
            mAltitudeRange = new Vector2ValueLE(requestedApiVersion, handler, stream); // (-10000.0f, 10000.0f)

            s.Read(out mForceMapId);
            s.Read(out mEmitRateMapId);
            s.Read(out mEmitColorMapId);
            mRandomWalk = new RandomWalk(requestedApiVersion, handler, stream);

            mAttractorOrigin = new Vector3ValueLE(requestedApiVersion, handler, stream);

            mAttractor = new Attractor(requestedApiVersion, handler, stream);

            mPathPoints = new DataList <PathPoint>(handler, stream);

            //Version 2+
            if (mSection.Version >= 0x0002 && stream.Position < stream.Length)
            {
                mVector01      = new Vector3ValueLE(requestedApiVersion, handler, stream);
                mVector3List01 = new DataList <Vector3ValueLE>(handler, stream);
            }

            //Version 3+
            if (mSection.Version >= 0x0003 && stream.Position < stream.Length)
            {
                s.Read(out mByte01);
            }

            //Version 4+
            if (mSection.Version >= 0x0004 && stream.Position < stream.Length)
            {
                s.Read(out mFloat01);
            }

            //Version 5+
            if (mSection.Version >= 0x0005 && stream.Position < stream.Length)
            {
                if (isTheSims4)
                {
                    mVector02 = new Vector3ValueLE(requestedApiVersion, handler, stream);
                    s.Read(out mUnknown170);
                }
                else
                {
                    float value;
                    s.Read(out value);
                    mVector02 = new Vector3ValueLE(requestedApiVersion, handler, value, value, value);
                }
            }

            if (isTheSims4)
            {
                //Version 6+
                if (mSection.Version >= 0x0006 && stream.Position < stream.Length)
                {
                    mUnknown140 = new Vector2ValueLE(requestedApiVersion, handler, stream);
                }
                else
                {
                    float value;
                    s.Read(out value);
                    mUnknown140 = new Vector2ValueLE(requestedApiVersion, handler, value, value);
                }

                //Version 7+
                if (mSection.Version >= 0x0007 && stream.Position < stream.Length)
                {
                    mUnknown150 = new Vector2ValueLE(requestedApiVersion, handler, stream);
                }

                s.Read(out mUnknown160);
                s.Read(out mUnknown164);

                s.Read(out mUnknown1C1);
                if (mUnknown1C1 != 0 && stream.Position < stream.Length)
                {
                    mUnknown180 = new Vector3ValueLE(requestedApiVersion, handler, stream);
                    s.Read(out mUnknown1C0);

                    if (mSection.Version >= 0x0006 && stream.Position < stream.Length)
                    {
                        mUnknown190 = new Vector2ValueLE(requestedApiVersion, handler, stream);
                    }
                    else
                    {
                        float value;
                        s.Read(out value);
                        mUnknown190 = new Vector2ValueLE(requestedApiVersion, handler, value, value);
                    }

                    if (mSection.Version >= 0x0007 && stream.Position < stream.Length)
                    {
                        mUnknown1A0 = new Vector2ValueLE(requestedApiVersion, handler, stream);
                    }

                    s.Read(out mUnknown1B0);
                    s.Read(out mUnknown1B4);
                }

                if (mSection.Version >= 0x0006 && stream.Position < stream.Length)
                {
                    s.Read(out mUnknown208);
                    if (mUnknown208 != 0)
                    {
                        s.Read(out mUnknown20C);
                        s.Read(out mUnknown209);
                        s.Read(out mUnknown20A);
                        s.Read(out mUnknown20B);
                    }
                }
            }
        }