Пример #1
0
        public void SparseArraySimpleTest()
        {
            var stringArrayRef = new string[1000];
            var stringArray = new SparseArray<string>(1000);

            var randomGenerator = new RandomGenerator(66707770); // make this deterministic
            for (int idx = 0; idx < 1000; idx++)
            {
                if (randomGenerator.Generate(2.0) > 1)
                { // add data.
                    stringArrayRef[idx] = idx.ToString();
                    stringArray[idx] = idx.ToString();
                }
                else
                {
                    stringArrayRef[idx] = null;
                    stringArray[idx] = null;
                }
            }

            for (int idx = 0; idx < 1000; idx++)
            {
                Assert.AreEqual(stringArrayRef[idx], stringArray[idx]);
            }
        }
Пример #2
0
 public void Generate(SparseArray<float> production, SparseArray<float> attractions)
 {
     float totalProduction = 0;
     float totalAttraction = 0;
     foreach (var zone in production.ValidIndexies())
     {
         float prod, attr;
         production[zone] = (prod = this.PopulationFactor * production[zone]);
         attractions[zone] = (attr = this.EmploymentFactor * attractions[zone]);
         totalProduction += prod;
         totalAttraction += attr;
     }
     if (totalAttraction <= 0)
     {
         throw new XTMF.XTMFRuntimeException("There is no employment in the zone system!");
     }
     else if (totalProduction <= 0)
     {
         throw new XTMF.XTMFRuntimeException("There is no population in the zone system!");
     }
     // Normalize the attractions
     var inverseTotalAttraction = 1 / totalAttraction; // inverse totalAttraction to save on divisions
     foreach (var zone in Root.ZoneSystem.ZoneArray.ValidIndexies())
     {
         attractions[zone] = (attractions[zone] * inverseTotalAttraction) * totalProduction;
     }
 }
Пример #3
0
        public override void Run()
        {
            var numberOfCategories = this.Categories.Count;
            SparseArray<float>[] O = new SparseArray<float>[numberOfCategories];
            SparseArray<float>[] D = new SparseArray<float>[numberOfCategories];

            Generation = true;
            for ( int i = 0; i < numberOfCategories; i++ )
            {
                O[i] = Root.ZoneSystem.ZoneArray.CreateSimilarArray<float>();
                D[i] = Root.ZoneSystem.ZoneArray.CreateSimilarArray<float>();
                this.Categories[i].Generate( O[i], D[i] );
            }
            Generation = false;

            var modeSplit = this.ModeSplit.ModeSplit( this.Distribution.Distribute( O, D, this.Categories ), this.Categories.Count );
            if ( this.Transpose )
            {
                TransposeMatrix( modeSplit );
            }
            if ( this.SaveOutput )
            {
                if ( !Directory.Exists( this.PurposeName ) )
                {
                    Directory.CreateDirectory( this.PurposeName );
                }
                for ( int i = 0; i < modeSplit.Count; i++ )
                {
                    this.WriteModeSplit( modeSplit[i], this.Root.Modes[i], this.PurposeName );
                }
            }
            this.Flows = modeSplit;
        }
Пример #4
0
 public void TestCSVODC()
 {
     try
     {
         int[] zones = new int[] { 0, 1, 2, 3, 4, 5, 6 };
         SparseArray<int> referenceArray = new SparseArray<int>( new SparseIndexing()
         {
             Indexes = new SparseSet[]
         {
             new SparseSet() { Start = 0, Stop = 6 }
         }
         } );
         float[][][] allData = new float[1][][];
         var data = CreateData( zones.Length );
         CreateCSVFile( zones, data, "Test.csv" );
         allData[0] = data;
         var writer = new ODMatrixWriter<int>( referenceArray, 1, 1 );
         writer.LoadCSVTimes( "Test.csv", false, 0, 0 );
         writer.Save( "Test.odc", false );
         var odcFloatData = ConvertData( allData, zones.Length, 1, 1 );
         ValidateData( zones, odcFloatData, "Test.odc" );
     }
     finally
     {
         File.Delete( "Test.csv" );
         File.Delete( "Test.odc" );
     }
 }
Пример #5
0
        public override void Generate(SparseArray<float> production, SparseArray<float> attractions)
        {
            if ( LoadData )
            {
                if ( DailyRates == null )
                {
                    this.LoadDailyRates.LoadData();
                    this.DailyRates = this.LoadDailyRates.GiveData();
                }
                if ( TimeOfDayRates == null )
                {
                    this.LoadTimeOfDayRates.LoadData();
                    this.TimeOfDayRates = this.LoadTimeOfDayRates.GiveData();
                }
            }
            var flatProduction = production.GetFlatData();
            var flatAttraction = attractions.GetFlatData();

            var numberOfIndexes = flatAttraction.Length;

            // Compute the Production and Attractions
            ComputeProduction( flatProduction, flatAttraction, numberOfIndexes );

            //We do not normalize the attraction
            if ( LoadData )
            {
                this.LoadDailyRates.UnloadData();
                this.LoadTimeOfDayRates.UnloadData();
                DailyRates = null;
                TimeOfDayRates = null;
            }
        }
Пример #6
0
        public override void Generate(SparseArray<float> production, SparseArray<float> attractions)
        {
            if ( LoadData )
            {
                if ( DailyRates == null )
                {
                    this.LoadDailyRates.LoadData();
                    this.DailyRates = this.LoadDailyRates.GiveData();
                }
                if ( TimeOfDayRates == null )
                {
                    this.LoadTimeOfDayRates.LoadData();
                    this.TimeOfDayRates = this.LoadTimeOfDayRates.GiveData();
                }
            }
            var flatProduction = production.GetFlatData();
            var numberOfIndexes = flatProduction.Length;

            // Compute the Production
            ComputeProduction( flatProduction, numberOfIndexes );
            float totalProduction = flatProduction.Sum();
            WriteGenerationCSV( totalProduction );
            //The PoRPoS Model does NOT include having an attraction component.  The distribution will handle this case.
            if ( LoadData )
            {
                this.DailyRates = null;
                this.TimeOfDayRates = null;
            }
        }
Пример #7
0
        public override void Generate(SparseArray<float> production, SparseArray<float> attractions)
        {
            if(LoadData)
            {
                LoadExternalWorkerRates.LoadData();
                LoadWorkAtHomeRates.LoadData();
                LoadExternalJobsRates.LoadData();
                ExternalRates = LoadExternalWorkerRates.GiveData();
                WorkAtHomeRates = LoadWorkAtHomeRates.GiveData();
                ExternalRates = LoadExternalJobsRates.GiveData();
            }
            var flatProduction = production.GetFlatData();
            var flatWah = new float[flatProduction.Length];
            var totalProduction = ComputeProduction(flatProduction, flatWah);
            var totalAttraction = ComputeAttraction(attractions.GetFlatData());

            Normalize(production.GetFlatData(), attractions.GetFlatData(), totalProduction, totalAttraction);
            totalAttraction = RemoveWAHFromAttraction(attractions.GetFlatData(), flatWah);
            StoreProductionData(production);
            WriteGenerationFile(totalProduction, totalAttraction);
            WriteAttractionFile(attractions);
            if(LoadData)
            {
                LoadExternalWorkerRates.UnloadData();
                LoadWorkAtHomeRates.UnloadData();
                LoadExternalJobsRates.UnloadData();
                WorkAtHomeRates = null;
                ExternalRates = null;
                ExternalJobs = null;
            }
        }
Пример #8
0
 public EmmeMatrix(SparseArray<IZone> zoneSystem, float[][] data)
 {
     var zones = zoneSystem.GetFlatData();
     MagicNumber = EmmeMagicNumber;
     Version = 1;
     Type = DataType.Float;
     Dimensions = 2;
     float[] temp = new float[zones.Length * zones.Length];
     Indexes = new int[2][];
     for(int i = 0; i < Indexes.Length; i++)
     {
         var row = Indexes[i] = new int[zones.Length];
         for(int j = 0; j < row.Length; j++)
         {
             row[j] = zones[j].ZoneNumber;
         }
     }
     for(int i = 0; i < data.Length; i++)
     {
         Array.Copy(data[i], 0, temp, i * zones.Length, zones.Length);
     }
     FloatData = temp;
     DoubleData = null;
     SignedIntData = null;
     UnsignedIntData = null;
 }
Пример #9
0
 public override void Run()
 {
     if ( !this.Execute ) return;
     // we actually don't write our mode choice
     var numberOfCategories = this.Categories.Count;
     SparseArray<float>[] O = new SparseArray<float>[numberOfCategories];
     SparseArray<float>[] D = new SparseArray<float>[numberOfCategories];
     for ( int i = 0; i < O.Length; i++ )
     {
         O[i] = Root.ZoneSystem.ZoneArray.CreateSimilarArray<float>();
         D[i] = Root.ZoneSystem.ZoneArray.CreateSimilarArray<float>();
         this.Categories[i].Generate( O[i], D[i] );
     }
     // if we only need to run generation we are done
     if ( this.OnlyDoGeneration ) return;
     // we don't do mode choice
     foreach ( var distributionData in this.Distribution.Distribute( O, D, this.Categories ) )
     {
         var interative = this.ModeSplit as IInteractiveModeSplit;
         if ( interative != null )
         {
             interative.EndInterativeModeSplit();
         }
         if ( !String.IsNullOrWhiteSpace( this.SaveResultFileName ) )
         {
             SaveFriction( distributionData.GetFlatData() );
         }
     }
 }
Пример #10
0
        public void Generate(SparseArray<float> production, SparseArray<float> attractions)
        {
            var ages = this.Root.Demographics.AgeRates;
            var studentRates = this.Root.Demographics.SchoolRates.GetFlatData();
            var zones = this.Root.ZoneSystem.ZoneArray.GetFlatData();
            var prod = production.GetFlatData();

            for ( int i = 0; i < zones.Length; i++ )
            {
                // this is only null for externals
                var studentRatesForZone = studentRates[i];
                if ( studentRatesForZone == null )
                {
                    // if it is an external ignore
                    prod[i] = 0f;
                }
                else
                {
                    // otherwise compute the production
                    var pd = zones[i].PlanningDistrict;
                    prod[i] = zones[i].Population * ages[zones[i].ZoneNumber, this.Age] * studentRatesForZone[this.Age, 0] *
                        StudentDailyRates[pd, 0, this.Age] * StudentTimeOfDayRates[pd, 0, this.Age];
                }
            }

            SaveProductionToDisk( zones, prod );
        }
Пример #11
0
        public void GettingNonExistingReturnsNull()
        {
            var array = new SparseArray<string>();

            Assert.IsNull(array.GetValue(10000));

            // We shouldn't have allocated items.

            Assert.AreEqual("Values=20", array.ToString());
        }
        private SparseArray<DataRenderer> GetRenderers(IEntity entity) {
            SparseArray<DataRenderer> renderers;

            if (_renderers.TryGetValue(entity.UniqueId, out renderers) == false) {
                renderers = new SparseArray<DataRenderer>();
                _renderers[entity.UniqueId] = renderers;
            }

            return renderers;
        }
Пример #13
0
        public void SetOneHundredElements()
        {
            SparseArray<int> array = new SparseArray<int>(10);

            for (int k = 0; k < 100; k++)
                array[(ulong)k] = k;

            for (int k = 0; k < 100; k++)
                Assert.AreEqual(k, array[(ulong)k]);
        }
Пример #14
0
        public void GetNegativeShouldNotFail()
        {
            var array = new SparseArray<string>();

            Assert.IsNull(array.GetValue(-10));

            // We shouldn't have allocated items.

            Assert.AreEqual("Values=20", array.ToString());
        }
Пример #15
0
        public SparseTwinIndex<float> ProcessFlow(SparseArray<float> O, SparseArray<float> D, int[] validIndexes, SparseArray<float> attractionStar = null)
        {
            int length = validIndexes.Length;
            Productions = O;
            Attractions = D;
            if(attractionStar == null)
            {
                AttractionsStar = D.CreateSimilarArray<float>();
            }
            else
            {
                AttractionsStar = attractionStar;
            }
            FlowMatrix = Productions.CreateSquareTwinArray<float>();
            if(Friction == null)
            {
                InitializeFriction(length);
            }
            var flatAttractionStar = AttractionsStar.GetFlatData();
            float[] oldTotal = new float[flatAttractionStar.Length];
            var flatAttractions = Attractions.GetFlatData();
            for(int i = 0; i < length; i++)
            {
                flatAttractionStar[i] = 1f;
                oldTotal[i] = flatAttractions[i];
            }
            int iteration = 0;
            float[] columnTotals = new float[length];
            var balanced = false;
            do
            {
                if(ProgressCallback != null)
                {
                    // this doesn't go to 100%, but that is alright since when we end, the progress
                    // of the calling model should assume we hit 100%
                    ProgressCallback(iteration / (float)MaxIterations);
                }
                Array.Clear(columnTotals, 0, columnTotals.Length);
                if(Vector.IsHardwareAccelerated)
                {
                    VectorProcessFlow(columnTotals, FlowMatrix.GetFlatData());
                }
                else
                {
                    ProcessFlow(columnTotals);
                }
                balanced = Balance(columnTotals, oldTotal);
            } while((++iteration) < MaxIterations && !balanced);

            if(ProgressCallback != null)
            {
                ProgressCallback(1f);
            }
            return FlowMatrix;
        }
Пример #16
0
        public void TestSparseArraySimple()
        {
            // intialize.
            var array = new SparseArray<int>(10);

            // fill and resize in the process.
            for (int idx = 0; idx < 1000; idx++)
            {
                if (idx >= array.Length)
                {
                    array.Resize(idx + 100);
                }
                array[idx] = idx;
            }
            for (int idx = 5000; idx < 10000; idx++)
            {
                if (idx >= array.Length)
                {
                    array.Resize(idx + 100);
                }
                array[idx] = idx;
            }

            // test content.
            for (int idx = 0; idx < 1000; idx++)
            {
                Assert.AreEqual(idx, array[idx]);
            }
            for (int idx = 1001; idx < 5000; idx++)
            {
                Assert.AreEqual(0, array[idx]);
            }
            for (int idx = 5000; idx < 10000; idx++)
            {
                Assert.AreEqual(idx, array[idx]);
            }

            // test enumerator.
            var list = new List<int>(array);
            for (int idx = 0; idx < 1000; idx++)
            {
                Assert.AreEqual(idx, list[idx]);
            }
            for (int idx = 1001; idx < 5000; idx++)
            {
                Assert.AreEqual(0, list[idx]);
            }
            for (int idx = 5000; idx < 10000; idx++)
            {
                Assert.AreEqual(idx, list[idx]);
            }
        }
Пример #17
0
        public void SetOneThousandSparseElements()
        {
            SparseArray<int> array = new SparseArray<int>(10);

            for (int k = 0; k < 1000; k++)
            {
                array[(ulong)(k*1000)] = k;
                Assert.AreEqual(k, array[(ulong)(k*1000)]);
            }

            for (int k = 0; k < 1000; k++)
                Assert.AreEqual(k, array[(ulong)(k*1000)]);
        }
Пример #18
0
        public static SparseTwinIndex<float> Process(SparseArray<float> production, float[] friction)
        {
            var ret = production.CreateSquareTwinArray<float>();
            var flatRet = ret.GetFlatData();
            var flatProduction = production.GetFlatData();
            var numberOfZones = flatProduction.Length;
            try
            {
                // Make all of the frictions to the power of E
                Parallel.For( 0, friction.Length, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount },
                    delegate(int i)
                    {
                        friction[i] = (float)Math.Exp( friction[i] );
                    } );

                Parallel.For( 0, numberOfZones, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount },
                    delegate(int i)
                    {
                        float sum = 0f;
                        var iIndex = i * numberOfZones;
                        // gather the sum of the friction
                        for ( int j = 0; j < numberOfZones; j++ )
                        {
                            sum += friction[iIndex + j];
                        }
                        if ( sum <= 0 )
                        {
                            return;
                        }
                        sum = 1f / sum;
                        for ( int j = 0; j < numberOfZones; j++ )
                        {
                            flatRet[i][j] = flatProduction[i] * ( friction[iIndex + j] * sum );
                        }
                    } );
            }
            catch ( AggregateException e )
            {
                if ( e.InnerException is XTMFRuntimeException )
                {
                    throw new XTMFRuntimeException( e.InnerException.Message );
                }
                else
                {
                    throw new XTMFRuntimeException( e.InnerException.Message + "\r\n" + e.InnerException.StackTrace );
                }
            }
            return ret;
        }
Пример #19
0
        public void SetOneThousandElements()
        {
            SparseArray<int> array = new SparseArray<int>(10);

            for (int k = 0; k < 1000; k++)
            {
                array[(ulong)k] = k;
                Assert.AreEqual(k, array[(ulong)k]);
                if (k>1)
                    Assert.AreEqual(1, array[1], string.Format("One lost at {0}", k));
            }

            for (int k = 0; k < 1000; k++)
                Assert.AreEqual(k, array[(ulong)k]);
        }
Пример #20
0
        public ArrayObject(Environment env, uint length)
            : base(env, env.Maps.Array, env.Prototypes.Array)
        {
            this.length = length;

            if (length > 0x20000)
            {
                this.sparse = new SparseArray();
                this.isDense = false;
            }
            else
            {
                this.dense = new Descriptor[length];
                this.isDense = true;
            }
        }
Пример #21
0
        public ArrayObject(Environment env, uint length)
            : base(env, env.Maps.Array, env.Prototypes.Array)
        {
            this.length = length;

            if (length > 0x20000)
            {
                this.sparse = new SparseArray();
                this.isDense = false;
            }
            else
            {
                this.dense = new Descriptor[length];
                this.isDense = true;
            }
            this.Put("length", (double)length, DescriptorAttrs.DontEnum);
        }
Пример #22
0
        public World(Game game, Renderer renderer)
        {
            this.Game = game;
            this.Renderer = renderer;

            Entities = new SparseArray<Entity>();
            Transformations = new SparseArray<Transformation>();
            Primitives = new SparseArray<Primitive>();
            Newtonians = new SparseArray<Newtonian>();
            Models = new SparseArray<Microsoft.Xna.Framework.Graphics.Model>();
            Players = new SparseArray<Player>();
            PlayerControls = new SparseArray<PlayerControl>();

            newtonianSystem = new NewtonianSystem(this);
            renderingSystem = new RenderingSystem(this, renderer);
            networkSystem = new NetworkSystem(this);
            inputSystem = new InputManager(this);
        }
Пример #23
0
 public void Generate(SparseArray<float> production, SparseArray<float> attractions)
 {
     var zones = this.Root.ZoneSystem.ZoneArray.GetFlatData();
     var numberOfzones = zones.Length;
     var flatProduction = production.GetFlatData();
     for ( int i = 0; i < numberOfzones; i++ )
     {
         int regionIndex;
         if ( !this.InverseLookup( zones[i].RegionNumber, out regionIndex ) )
         {
             // if this region is not included just continue
             flatProduction[i] = 0;
             continue;
         }
         flatProduction[i] = zones[i].Population * this.RegionPopulationParameter[regionIndex]
             + zones[i].Employment * this.RegionEmploymentParameter[regionIndex]
             + this.RegionConstantsParameter[regionIndex];
     }
 }
Пример #24
0
        public override void Generate(SparseArray<float> production, SparseArray<float> attractions)
        {
            if ( LoadData && Rates == null )
            {
                this.LoadRates.LoadData();
                this.Rates = this.LoadRates.GiveData();
            }
            this.InitializeDemographicCategory();
            var flatProduction = production.GetFlatData();
            var numberOfIndexes = flatProduction.Length;

            // Compute the Production
            float totalProduction = 0;
            totalProduction = ComputeProduction( flatProduction, numberOfIndexes );
            SaveGenerationData( totalProduction );
            //The HBO Model does NOT include having an attraction component.  The distribution will handle this case.
            if ( LoadData )
            {
                this.Rates = null;
            }
        }
Пример #25
0
        public void CorrectKeysWithInsertsWithSpaces()
        {
            var array = new SparseArray<string>();

            for (int i = 0; i < 1000; i++)
            {
                if (i % 2 == 0)
                    array.SetValue(i, i.ToString());
            }

            int offset = 0;
            foreach (int key in array.GetKeys())
            {
                Assert.AreEqual(offset, key);
                offset += 2;
            }

            // Verify that we didn't switch to chunks even though we have
            // sparsely set items.

            Assert.AreEqual("Values=1280", array.ToString());
        }
Пример #26
0
        public void InsertAtHighIndex()
        {
            var array = new SparseArray<string>();
            int offset = 1000000;

            // Insert some items.

            for (int i = 0; i < 1000; i++)
            {
                array.SetValue(offset + i, i.ToString());
            }

            // Verify that we can get them back.

            for (int i = 0; i < 1000; i++)
            {
                Assert.AreEqual(i.ToString(), array.GetValue(offset + i));
            }

            // Verify that we've switched to chunks.

            Assert.AreEqual("Chunks=33, ChunkCapacity=37", array.ToString());
        }
Пример #27
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            imageview  = FindViewById <ImageView>(Resource.Id.image_view);
            btnProcess = FindViewById <Button>(Resource.Id.btnProcess);
            txtView    = FindViewById <TextView>(Resource.Id.txtView);

            Bitmap bitmap = BitmapFactory.DecodeResource(ApplicationContext.Resources, Resource.Drawable.csharpcorner);

            imageview.SetImageBitmap(bitmap);

            btnProcess.Click += delegate
            {
                TextRecognizer txtRecognizer = new TextRecognizer.Builder(ApplicationContext).Build();
                if (!txtRecognizer.IsOperational)
                {
                    Log.Error("Error", "Detector dependencies are not yet available");
                }
                else
                {
                    Frame         frame      = new Frame.Builder().SetBitmap(bitmap).Build();
                    SparseArray   items      = txtRecognizer.Detect(frame);
                    StringBuilder strBuilder = new StringBuilder();
                    for (int i = 0; i < items.Size(); i++)
                    {
                        TextBlock item = (TextBlock)items.ValueAt(i);
                        strBuilder.Append(item.Value);
                        strBuilder.Append("/");
                    }
                    txtView.Text = strBuilder.ToString();
                }
            };
        }
        public void ReceiveDetections(Detections detections)
        {
            SparseArray  items   = detections.DetectedItems;
            const string Pattern = "#.*?#";
            Regex        regex   = new Regex(Pattern);


            string found = "";

            if (items.Size() != 0)
            {
                textView.Post(() => {
                    StringBuilder strBuilder = new StringBuilder();
                    for (int i = 0; i < items.Size(); i++)
                    {
                        //Match match = regex.Match(((TextBlock)items.ValueAt(i)).Value);
                        //if (match.Success)
                        //{
                        //    found = match.Value;
                        //    cameraSource.Stop();
                        //}
                        ////else
                        ////{
                        ////    strBuilder.Append(((TextBlock)items.ValueAt(i)).Value);
                        ////    strBuilder.Append("\n");
                        ////}
                        strBuilder.Append(((TextBlock)items.ValueAt(i)).Value);
                        strBuilder.Append("\n");
                    }
                    //if (found != "")
                    //textView.Text = found;

                    textView.Text = strBuilder.ToString();
                    //else
                });
            }
        }
Пример #29
0
        //(Metodo de IProcessor) Metodo que recibe de la API de Google el texto detectado.
        public void ReceiveDetections(Detections detections)
        {
            SparseArray      items       = detections.DetectedItems;
            List <TextBlock> listaTexto  = new List <TextBlock>();
            StringBuilder    cadenaTexto = new StringBuilder();

            //Funcion Lambda
            texto.Post(() =>
            {
                for (int cont = 0; cont < items.Size(); cont++)
                {
                    //Agrega los "bloques de texto" a listaTexto
                    listaTexto.Add((TextBlock)items.ValueAt(cont));
                }
                foreach (TextBlock item in listaTexto)
                {
                    //Adjunta TextBlock on a StringBuilder
                    cadenaTexto.Append(item.Value);
                    cadenaTexto.Append("\n");
                }
                //Actualiza el TextView
                texto.Text = cadenaTexto.ToString();
                // Creacion del archivo de texto en la memoria del dispositivo
                if (capturarTexto)
                {
                    //Creacion del nombre del archivo guardado (En este caso se usa la fecha actual como nombre).
                    String nombreArchivo = DateTime.Now.ToString();
                    //Quitar caracteres invalidos para los nombres de archivo.
                    nombreArchivo = nombreArchivo.Replace(':', '-');
                    nombreArchivo = nombreArchivo.Replace('/', '-');
                    //Creación de la ruta completa con la ruta mas el nombre del archivo.
                    string rutaCompleta = System.IO.Path.Combine(ruta, nombreArchivo.ToString() + ".txt");
                    GeneradorArchivos(cadenaTexto, rutaCompleta);
                    Toast.MakeText(this.ApplicationContext, "Texto Capturado!", ToastLength.Short).Show();
                }
            });
        }
Пример #30
0
        public static bool ValidateLotteryReceipt(SparseArray items)
        {
            for (int i = 0; i < items.Size(); i++)
            {
                var itemComponents = ((TextBlock)items.ValueAt(i)).Components;
                for (int j = 0; j < itemComponents.Count; j++)
                {
                    if (_cashRegisterNumber != null && _receiptDate != null && _receiptNumber != null)
                    {
                        return(true);
                    }

                    var line = itemComponents[j].Value;

                    if (line.Contains("PVM") || line.Contains("LT"))
                    {
                        break;
                    }

                    if (_receiptNumber == null)
                    {
                        ReceiptNumberValidation(line);
                    }

                    if (_receiptDate == null)
                    {
                        ReceiptDateValidation(line);
                    }

                    if (_cashRegisterNumber == null)
                    {
                        CashRegisterNumberValidation(line);
                    }
                }
            }
            return(false);
        }
Пример #31
0
        private void WriteAttractionFile(SparseArray <float> productions, SparseArray <float> attractions)
        {
            if (!this.AttractionFileName.ContainsFileName())
            {
                return;
            }
            var           flatAttractions = attractions.GetFlatData();
            var           flatProduction  = productions.GetFlatData();
            bool          first           = !File.Exists(this.AttractionFileName.GetFileName());
            StringBuilder buildInside     = new StringBuilder();

            buildInside.Append(',');
            buildInside.Append(this.AgeCategoryRange.ToString());
            buildInside.Append(',');
            buildInside.Append(this.EmploymentStatusCategory.ToString());
            buildInside.Append(',');
            buildInside.Append(this.OccupationCategory.ToString());
            buildInside.Append(',');
            string categoryData = buildInside.ToString();

            using (StreamWriter writer = new StreamWriter(this.AttractionFileName.GetFileName(), true))
            {
                if (first)
                {
                    // if we are the first thing to generate, then write the header as well
                    writer.WriteLine("Zone,Age,Employment,Occupation,Production,Attraction");
                }
                for (int i = 0; i < flatAttractions.Length; i++)
                {
                    writer.Write(attractions.GetSparseIndex(i));
                    writer.Write(categoryData);
                    writer.Write(flatProduction[i]);
                    writer.Write(',');
                    writer.WriteLine(flatAttractions[i]);
                }
            }
        }
Пример #32
0
        private float[] LoadWorkerCategories(IZone[] zones, SparseArray <IZone> zoneArray)
        {
            if ((!ReloadWorkerCategories) & (WorkerCategories != null))
            {
                return(WorkerCategories);
            }
            var ret = new float[zones.Length * NumberOfWorkerCategories];

            using (CsvReader reader = new CsvReader(WorkerCategorySplits))
            {
                //burn header
                int columns;
                reader.LoadLine(out columns);
                // read data
                while (reader.LoadLine(out columns))
                {
                    if (columns < 3)
                    {
                        continue;
                    }
                    int   zone, category;
                    float probability;
                    reader.Get(out zone, 0);
                    reader.Get(out category, 1);
                    reader.Get(out probability, 2);
                    zone = zoneArray.GetFlatIndex(zone);
                    // categories are 1 indexed however we want 0 indexed
                    category -= 1;
                    if (zone < 0 | category < 0 | category >= NumberOfWorkerCategories)
                    {
                        continue;
                    }
                    ret[zone + (zones.Length * category)] = probability;
                }
            }
            return(WorkerCategories = ret);
        }
Пример #33
0
 public override void Generate(SparseArray<float> production, SparseArray<float> attractions)
 {
     // Do nothing, the distribution needs to do it all anyways
     // The only thing this generation needs is the ability to setup the mode choice properly
     var flatProduction = production.GetFlatData();
     var ageRates = this.Root.Demographics.AgeRates;
     var empRates = this.Root.Demographics.EmploymentStatusRates.GetFlatData();
     var occRates = this.Root.Demographics.OccupationRates.GetFlatData();
     var zones = this.Root.ZoneSystem.ZoneArray.GetFlatData();
     var age = this.AgeCategoryRange[0].Start;
     var occ = this.OccupationCategory[0].Start;
     Parallel.For( 0, flatProduction.Length, (int i) =>
     {
         float total = 0;
         var zoneNumber = zones[i].ZoneNumber;
         var emp = empRates[i];
         var occRate = occRates[i];
         if ( emp == null | occRate == null )
         {
             flatProduction[i] = 0;
         }
         else
         {
             foreach ( var set in this.AllAges )
             {
                 for ( int a = set.Start; a <= set.Stop; a++ )
                 {
                     total += ageRates[zoneNumber, a] * emp[a, 1] * occRate[a, 1, occ];
                 }
             }
             // NOTE, SINCE THE DISTRIBUTION DOES TRIP RATES BASED ON  PDO->PDD WE ONLY NEED TO
             // GIVE THE TOTAL WORKERS FOR THIS GIVEN AGE
             // the rate is not just the age, but the weight of the age for valid workers
             flatProduction[i] = total > 0 ? ( ageRates[zoneNumber, age] * emp[age, 1] * occRate[age, 1, occ] ) / total : 0;
         }
     } );
 }
Пример #34
0
        public override void Run()
        {
            if (!this.Execute)
            {
                return;
            }
            // we actually don't write our mode choice
            var numberOfCategories = this.Categories.Count;

            SparseArray <float>[] O = new SparseArray <float> [numberOfCategories];
            SparseArray <float>[] D = new SparseArray <float> [numberOfCategories];
            for (int i = 0; i < O.Length; i++)
            {
                O[i] = Root.ZoneSystem.ZoneArray.CreateSimilarArray <float>();
                D[i] = Root.ZoneSystem.ZoneArray.CreateSimilarArray <float>();
                this.Categories[i].Generate(O[i], D[i]);
            }
            // if we only need to run generation we are done
            if (this.OnlyDoGeneration)
            {
                return;
            }
            // we don't do mode choice
            foreach (var distributionData in this.Distribution.Distribute(O, D, this.Categories))
            {
                var interative = this.ModeSplit as IInteractiveModeSplit;
                if (interative != null)
                {
                    interative.EndInterativeModeSplit();
                }
                if (!String.IsNullOrWhiteSpace(this.SaveResultFileName))
                {
                    SaveFriction(distributionData.GetFlatData());
                }
            }
        }
Пример #35
0
        public void LoadData()
        {
            var zoneArray = Root.ZoneSystem.ZoneArray;
            var zones     = zoneArray.GetFlatData();
            var resources = ResourcesToAdd.Select(resource => resource.AcquireResource <SparseArray <float> >().GetFlatData()).Union(
                ResourcesToAddRaw.Select(source =>
            {
                source.LoadData();
                var ret = source.GiveData();
                source.UnloadData();
                return(ret.GetFlatData());
            })
                ).ToArray();
            SparseArray <float> data;

            data = SaveRatesBasedOnPD ? ZoneSystemHelper.CreatePDArray <float>(zoneArray) : zoneArray.CreateSimilarArray <float>();
            var flatData = data.GetFlatData();

            for (int j = 0; j < resources.Length; j++)
            {
                VectorHelper.Add(flatData, 0, flatData, 0, resources[j], 0, flatData.Length);
            }
            Data = data;
        }
Пример #36
0
        public void ReceiveDetections(Detections detections)
        {
            SparseArray items = detections.DetectedItems;

            if (items.Size() != 0)
            {
                txtView.Post(() => {
                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.Append(((TextBlock)items.ValueAt(0)).Value);
                    strBuilder.Append("\n");
                    str            = strBuilder.ToString();
                    string str_num = "";
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (str[i] >= '0' && str[i] <= '9')
                        {
                            str_num += str[i].ToString();
                        }
                    }
                    txtView.Text = str_num;
                    flag         = true;
                });
            }
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: DeviceActionsLayoutData(com.samsung.android.sdk.professionalaudio.app.SapaAppInfo info, android.content.Context context, boolean isMultiInstance) throws android.content.pm.PackageManager.NameNotFoundException
        internal DeviceActionsLayoutData(SapaAppInfo info, Context context, bool isMultiInstance)
        {
            mAppInfo                  = info;
            this.mInstanceIcon        = info.getIcon(context);
            this.mSapaApp             = info.App;
            this.mInstancePackageName = info.PackageName;
            this.mActionList          = info.Actions;
            if (this.mActionList == null)
            {
                this.mActionList = new SparseArray <SapaActionInfo>();
            }
            mActionMap = new Dictionary <string, SapaActionInfo>();
            loadActionMap();
            this.mIsMultiInstanceEnabled = info.MultiInstanceEnabled;
            if (this.mIsMultiInstanceEnabled && isMultiInstance)
            {
                char c = this.mSapaApp.InstanceId.charAt(this.mSapaApp.InstanceId.length() - 1);
                number = char.digit(c, 10);
                if (number > 0)
                {
                    mInstanceIcon = DrawableTool.getDefaultDrawableWithNumber(mInstanceIcon, number, context);
                }
            }
        }
Пример #38
0
        public List <Anchor> CalculateAnchors(IList <CalendarItem> calendarItems, bool hasCalendarsLinked)
        {
            var calendarEvents  = new List <CalendarItem>();
            var timeEntries     = new List <CalendarItem>();
            var originalIndexes = new Dictionary <CalendarItem, int>(calendarItems.Count);
            var adapterIndex    = anchorCount;

            foreach (var calendarItem in calendarItems)
            {
                if (calendarItem.Source == CalendarItemSource.TimeEntry)
                {
                    timeEntries.Add(calendarItem);
                }
                else
                {
                    calendarEvents.Add(calendarItem);
                }
                originalIndexes.Add(calendarItem, adapterIndex++);
            }

            var newAnchors = new SparseArray <IList <AnchorData> >(anchorCount);

            if (hasCalendarsLinked || calendarEvents.Count > 0)
            {
                calculateAttributes(calendarEvents, halfAvailableWidth, leftMargin, originalIndexes, newAnchors);
                calculateAttributes(timeEntries, halfAvailableWidth, leftMargin + halfAvailableWidth, originalIndexes, newAnchors);
            }
            else
            {
                calculateAttributes(timeEntries, availableWidth, leftMargin, originalIndexes, newAnchors);
            }

            return(Enumerable.Range(0, anchorCount)
                   .Select(anchor => new Anchor((int)hourHeight, newAnchors.Get(anchor, emptyAnchorData).ToArray()))
                   .ToList());
        }
Пример #39
0
        private bool AreWeClosest(IZone origin, SparseArray <IZone> zoneArray, SparseTwinIndex <float> distances)
        {
            var ourDistance = distances[origin.ZoneNumber, InterchangeZone.ZoneNumber];

            foreach (var range in StationRanges)
            {
                for (int i = range.Start; i <= range.Stop; i++)
                {
                    if (i == StationZone)
                    {
                        continue;
                    }
                    var otherZone = zoneArray[i];
                    if (otherZone != null)
                    {
                        if (distances[origin.ZoneNumber, otherZone.ZoneNumber] < ourDistance)
                        {
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
Пример #40
0
 private ComputationResult LengthColumns(ComputationResult computationResult)
 {
     if (computationResult.IsOdResult)
     {
         var data     = computationResult.OdData;
         var ret      = new SparseArray <float>(data.Indexes);
         var flatRet  = ret.GetFlatData();
         var flatData = data.GetFlatData();
         System.Threading.Tasks.Parallel.For(0, flatData.Length, (int i) =>
         {
             int temp = 0;
             for (int j = 0; j < flatData.Length; j++)
             {
                 if (flatData[j].Length > i)
                 {
                     temp++;
                 }
             }
             flatRet[i] = temp;
         });
         return(new ComputationResult(ret, true, ComputationResult.VectorDirection.Horizontal));
     }
     return(new ComputationResult("An unknown data type was processed through LengthColumns!"));
 }
Пример #41
0
        public void LoadData()
        {
            var zoneArray            = this.Root.ZoneSystem.ZoneArray;
            var zones                = zoneArray.GetFlatData();
            var firstRate            = this.FirstRateToApply.AquireResource <SparseArray <float> >();
            var secondRate           = this.SecondRateToApply.AquireResource <SparseArray <float> >();
            SparseArray <float> data = firstRate.CreateSimilarArray <float>();
            var flatFirst            = firstRate.GetFlatData();
            var flatSecond           = secondRate.GetFlatData();
            var flat = data.GetFlatData();

            if (VectorHelper.IsHardwareAccelerated)
            {
                VectorHelper.Divide(flat, 0, flatFirst, 0, flatSecond, 0, flat.Length);
            }
            else
            {
                for (int i = 0; i < flat.Length; i++)
                {
                    flat[i] = flatFirst[i] / flatSecond[i];
                }
            }
            this.Data = data;
        }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: DeviceActionsLayoutData(com.samsung.android.sdk.professionalaudio.app.SapaAppInfo info, android.content.Context context, boolean isMultiInstance) throws android.content.pm.PackageManager.NameNotFoundException
		internal DeviceActionsLayoutData(SapaAppInfo info, Context context, bool isMultiInstance)
		{
			mAppInfo = info;
			this.mInstanceIcon = info.getIcon(context);
			this.mSapaApp = info.App;
			this.mInstancePackageName = info.PackageName;
			this.mActionList = info.Actions;
			if (this.mActionList == null)
			{
				this.mActionList = new SparseArray<SapaActionInfo>();
			}
			mActionMap = new Dictionary<string, SapaActionInfo>();
			loadActionMap();
			this.mIsMultiInstanceEnabled = info.MultiInstanceEnabled;
			if (this.mIsMultiInstanceEnabled && isMultiInstance)
			{
				char c = this.mSapaApp.InstanceId.charAt(this.mSapaApp.InstanceId.length() - 1);
				number = char.digit(c, 10);
				if (number > 0)
				{
					mInstanceIcon = DrawableTool.getDefaultDrawableWithNumber(mInstanceIcon, number, context);
				}
			}
		}
Пример #43
0
        private void RecogText(Bitmap bitmap)
        {
            TextRecognizer txtRecognizer = new TextRecognizer.Builder(ApplicationContext).Build();

            if (!txtRecognizer.IsOperational)
            {
                Log.Error("Error", "Detector dependencies are not yet available");
            }
            else
            {
                frame = new Frame.Builder().SetBitmap(bitmap).Build();

                // Detect characters
                items = txtRecognizer.Detect(frame);

                // Create list for detected characters
                itemlist = new List <string>();

                // Add items to list
                for (int i = 0; i < items.Size(); i++)
                {
                    TextBlock item = (TextBlock)items.ValueAt(i);
                    itemlist.Add(item.Value);
                }

                // If no characters were found, print message
                if (itemlist.Count == 0)
                {
                    Toast.MakeText(this, "No characters found", ToastLength.Long).Show();
                }

                // Fill the listView with the items of itemlist
                ArrayAdapter <string> adapter = new ArrayAdapter <string>(this, Android.Resource.Layout.SimpleListItemActivated1, itemlist);
                listnames.Adapter = adapter;
            }
        }
Пример #44
0
        public void ReceiveDetections(Detections detections)
        {
            SparseArray items = detections.DetectedItems;

            if (items.Size() != 0)
            {
                for (int i = 0; i < items.Size(); i++)
                {
                    var line = ((TextBlock)items.ValueAt(i)).Value;
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }
                    if (line.Contains("<<<"))
                    {
                        textView.Text = line;
                        //cameraSource.TakePicture()
                        cameraSource.TakePicture(this, this);
                    }
                    if (line.Contains(">>>"))
                    {
                        textView.Text = line;
                    }
                }
                //textView.Post(() =>
                //{
                //    StringBuilder strBuilder = new StringBuilder();
                //    for (int i = 0; i < items.Size(); i++)
                //    {
                //        var line = ((TextBlock)items.ValueAt(i)).Value;
                //        if (string.IsNullOrEmpty(line)) continue;
                //    }
                //    textView.Text = strBuilder.ToString();
                //});
            }
        }
Пример #45
0
        public async Task <List <BarcodeResult> > ScanFromImage(byte[] imageArray)
        {
            BarcodeDetector detector = new BarcodeDetector.Builder(Android.App.Application.Context)
                                       .SetBarcodeFormats(Configuration.BarcodeFormats)
                                       .Build();
            Bitmap bitmap = BitmapFactory.DecodeByteArray(imageArray, 0, imageArray.Length);

            Android.Gms.Vision.Frame frame      = new Android.Gms.Vision.Frame.Builder().SetBitmap(bitmap).Build();
            SparseArray          qrcodes        = detector.Detect(frame);
            List <BarcodeResult> barcodeResults = new List <BarcodeResult>();

            for (int i = 0; i < qrcodes.Size(); i++)
            {
                Barcode barcode = qrcodes.ValueAt(i) as Barcode;
                var     type    = Methods.ConvertBarcodeResultTypes(barcode.ValueFormat);
                var     value   = barcode.DisplayValue;
                barcodeResults.Add(new BarcodeResult
                {
                    BarcodeType  = type,
                    DisplayValue = value
                });
            }
            return(barcodeResults);
        }
Пример #46
0
 public void UnloadData()
 {
     Loaded = false;
     Data   = null;
 }
Пример #47
0
 public void UnloadData()
 {
     this.Data = null;
 }
Пример #48
0
 public void UnloadData()
 {
     Loaded = false;
     _inflationRateByMonth = null;
 }
Пример #49
0
 public void LoadData()
 {
     _inflationRateByMonth = Repository.GetRepository(TemperalDataLoader);
     Loaded = true;
 }
Пример #50
0
 public void IterationStarting(int iteration)
 {
     ZoneSystem = Root.ZoneSystem.ZoneArray;
     if(Data == null)
     {
         Data = ZoneSystem.CreateSquareTwinArray<float>().GetFlatData();
     }
     else
     {
         for(int i = 0; i < Data.Length; i++)
         {
             Array.Clear(Data[i], 0, Data[i].Length);
         }
     }
     Activities = ActivitiesToCapture.Select(a => a.Activity).ToArray();
 }
Пример #51
0
        private float[][][] BuildData(string[] modeNames, SparseArray <IZone> zoneSystem, SparseArray <int> regions)
        {
            var zones           = zoneSystem.GetFlatData();
            var modes           = Root.AllModes.ToArray();
            var data            = new float[modes.Length][][];
            var numberOfRegions = regions.GetFlatData().Length;

            for (int i = 0; i < data.Length; i++)
            {
                var row = data[i] = new float[numberOfRegions][];
                for (int j = 0; j < row.Length; j++)
                {
                    row[j] = new float[numberOfRegions];
                }
            }
            using (CsvReader reader = new CsvReader(ZonalModeSplitFile))
            {
                // burn header
                reader.LoadLine();
                int columns;
                while (reader.LoadLine(out columns))
                {
                    // ignore lines without the right number of columns
                    if (columns == 4)
                    {
                        string modeName;
                        int    originZone, destinationZone;
                        float  expandedPersons;
                        reader.Get(out modeName, 0);
                        reader.Get(out originZone, 1);
                        reader.Get(out destinationZone, 2);
                        reader.Get(out expandedPersons, 3);
                        data[ModeIndex(modeName, modeNames)][regions.GetFlatIndex(zoneSystem[originZone].RegionNumber)][regions.GetFlatIndex(zoneSystem[destinationZone].RegionNumber)]
                            += expandedPersons;
                    }
                }
            }
            return(data);
        }
Пример #52
0
 /// <summary>
 /// Load the probabilities from file
 /// </summary>
 /// <param name="zoneSystem">The zone system the model is using</param>
 private void LoadProbabilities(SparseArray<IZone> zoneSystem)
 {
     var zones = zoneSystem.GetFlatData();
     AutoProbabilities = new float[zones.Length];
     TransitProbabilities = new float[zones.Length];
     TotalTrips = new float[zones.Length];
     using (CsvReader reader = new CsvReader(ModeSplitTruthData))
     {
         // burn header
         reader.LoadLine();
         // read in the rest of the data
         int columns;
         while(reader.LoadLine(out columns))
         {
             if(columns >= 3)
             {
                 int zone;
                 reader.Get(out zone, 0);
                 zone = zoneSystem.GetFlatIndex(zone);
                 if(zone >= 0)
                 {
                     float auto, transit, totalTrips;
                     reader.Get(out auto, 1);
                     reader.Get(out transit, 2);
                     reader.Get(out totalTrips, 3);
                     AutoProbabilities[zone] = auto;
                     TransitProbabilities[zone] = transit;
                     TotalTrips[zone] = totalTrips;
                 }
             }
         }
     }
 }
Пример #53
0
        private void Solve()
        {
            mainToolStripStatusLabel.Text = Properties.Resources.IDS_SOLVING_EQUATIONS;

            Sparse2DMatrix <int, int, double> aMatrix = new Sparse2DMatrix <int, int, double>();
            SparseArray <int, double>         bVector = new SparseArray <int, double>();
            SparseArray <string, int>         variableNameIndexMap = new SparseArray <string, int>();
            int numberOfEquations = 0;

            LinearEquationParser       parser       = new LinearEquationParser();
            LinearEquationParserStatus parserStatus = LinearEquationParserStatus.Success;

            foreach (string inputLine in equationsRichTextBox.Lines)
            {
                parserStatus = parser.Parse(inputLine,
                                            aMatrix,
                                            bVector,
                                            variableNameIndexMap,
                                            ref numberOfEquations);

                if (parserStatus != LinearEquationParserStatus.Success)
                {
                    break;
                }
            }

            // Assume success.
            string mainStatusBarText = Properties.Resources.IDS_EQUATIONS_SOLVED;

            // Did an error occur?
            if (parserStatus == LinearEquationParserStatus.Success)
            {
                // Are there the same number of equations as variables?
                if (numberOfEquations == variableNameIndexMap.Count)
                {
                    // Create a solution vector.
                    SparseArray <int, double> xVector = new SparseArray <int, double>();

                    // Solve the simultaneous equations.
                    LinearEquationSolverStatus solverStatus =
                        LinearEquationSolver.Solve(numberOfEquations,
                                                   aMatrix,
                                                   bVector,
                                                   xVector);

                    if (solverStatus == LinearEquationSolverStatus.Success)
                    {
                        string solutionString = "";

                        foreach (KeyValuePair <string, int> pair in variableNameIndexMap)
                        {
                            solutionString += string.Format("{0} = {1}", pair.Key, xVector[pair.Value]);
                            solutionString += "\n";
                        }

                        equationsRichTextBox.Text += "\n" + solutionString;
                    }
                    else if (solverStatus == LinearEquationSolverStatus.IllConditioned)
                    {
                        mainStatusBarText = Properties.Resources.IDS_ILL_CONDITIONED_SYSTEM_OF_EQUATIONS;
                    }
                    else if (solverStatus == LinearEquationSolverStatus.Singular)
                    {
                        mainStatusBarText = Properties.Resources.IDS_SINGULAR_SYSTEM_OF_EQUATIONS;
                    }
                }
                else if (numberOfEquations < variableNameIndexMap.Count)
                {
                    mainStatusBarText = string.Format(Properties.Resources.IDS_TOO_FEW_EQUATIONS,
                                                      numberOfEquations, variableNameIndexMap.Count);
                }
                else if (numberOfEquations > variableNameIndexMap.Count)
                {
                    mainStatusBarText = string.Format(Properties.Resources.IDS_TOO_MANY_EQUATIONS,
                                                      numberOfEquations, variableNameIndexMap.Count);
                }
            }
            else
            {
                // An error occurred. Report the error in the status bar.
                mainStatusBarText = LinearEquationParserStatusInterpreter.GetStatusString(parserStatus);
            }

            mainToolStripStatusLabel.Text = mainStatusBarText;
        }
Пример #54
0
        public void LoadData()
        {
            var zoneArray = Root.ZoneSystem.ZoneArray;
            var zones     = zoneArray.GetFlatData();
            var data      = LocalData;

            if (data == null)
            {
                LocalData = data = new float[zones.Length * zones.Length * NumberOfWorkerCategories];
            }
            var distances = Root.ZoneSystem.Distances.GetFlatData();
            var pds       = PlanningDistricts;

            if (pds == null)
            {
                PlanningDistricts = pds = zones.Select((zone) => zone.PlanningDistrict).ToArray();
            }
            if (KeepLocalData)
            {
                CreateHighPerformanceLookup(zoneArray);
            }
            float[] workerSplits             = LoadWorkerCategories(zones, zoneArray);
            SparseTwinIndex <float> kFactors = null;

            if (KFactors != null)
            {
                kFactors = KFactors.AquireResource <SparseTwinIndex <float> >();
                Parallel.For(0, zones.Length, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                }, (int i) =>
                {
                    var distanceRow = distances[i];
                    var iPD         = pds[i];
                    for (int k = 0; k < NumberOfWorkerCategories; k++)
                    {
                        int offset = k * zones.Length * zones.Length + i * zones.Length;
                        for (int j = 0; j < zones.Length; j++)
                        {
                            // use distance in km
                            data[offset + j] = kFactors[iPD, pds[j]] * CalculateUtilityToE(iPD, pds[j], i, j, k, distanceRow[j] * 0.001f);
                        }
                    }
                });
                KFactors.ReleaseResource();
            }
            else
            {
                Parallel.For(0, zones.Length, new ParallelOptions()
                {
                    MaxDegreeOfParallelism = Environment.ProcessorCount
                }, (int i) =>
                {
                    var distanceRow = distances[i];
                    var iPD         = pds[i];
                    for (int k = 0; k < NumberOfWorkerCategories; k++)
                    {
                        int offset = k * zones.Length * zones.Length + i * zones.Length;
                        for (int j = 0; j < zones.Length; j++)
                        {
                            // use distance in km
                            data[offset + j] = CalculateUtilityToE(iPD, pds[j], i, j, k, distanceRow[j] * 0.001f);
                        }
                    }
                });
            }

            SparseArray <float> employmentSeekers = EmployedPopulationResidenceByZone.AquireResource <SparseArray <float> >();
            var jobs    = CreateNormalizedJobs(employmentSeekers, JobsByZone.AquireResource <SparseArray <float> >().GetFlatData());
            var results = TMG.Functions.GravityModel3D.ProduceFlows(MaxIterations, Epsilon,
                                                                    CreateWorkersByCategory(employmentSeekers, workerSplits),
                                                                    jobs, data,
                                                                    NumberOfWorkerCategories, zones.Length);

            Data = ConvertResults(results, zoneArray);
            if (!KeepLocalData)
            {
                LocalData         = null;
                PlanningDistricts = null;
                WorkerCategories  = null;
            }
            Loaded = true;
        }
Пример #55
0
 public void Dispose()
 {
     dict.Dispose(); parent = null;
 }
Пример #56
0
 public SparseArrayEnumerator(SparseArray <T> array)
 {
     parent = array; Reset();
 }
Пример #57
0
        public string SolveEquation(string equation)
        {
            Sparse2DMatrix <int, int, double> aMatrix = new Sparse2DMatrix <int, int, double>();
            SparseArray <int, double>         bVector = new SparseArray <int, double>();
            SparseArray <string, int>         variableNameIndexMap = new SparseArray <string, int>();
            int numberOfEquations = 0;

            LinearEquationParser       parser       = new LinearEquationParser();
            LinearEquationParserStatus parserStatus = LinearEquationParserStatus.Success;

            string[] lines = equation.Split(new[] { "\r\n", "\r", "\n", "\\n", "," }, StringSplitOptions.None);

            foreach (string inputLine in lines)
            {
                parserStatus = parser.Parse(inputLine,
                                            aMatrix,
                                            bVector,
                                            variableNameIndexMap,
                                            ref numberOfEquations);

                if (parserStatus != LinearEquationParserStatus.Success)
                {
                    break;
                }
            }

            // Assume success.
            string mainStatusBarText = "Equations solved";

            // Did an error occur?
            if (parserStatus == LinearEquationParserStatus.Success)
            {
                // Are there the same number of equations as variables?
                if (numberOfEquations == variableNameIndexMap.Count)
                {
                    // Create a solution vector.
                    SparseArray <int, double> xVector = new SparseArray <int, double>();

                    // Solve the simultaneous equations.
                    LinearEquationSolverStatus solverStatus =
                        LinearEquationSolver.Solve(numberOfEquations,
                                                   aMatrix,
                                                   bVector,
                                                   xVector);

                    if (solverStatus == LinearEquationSolverStatus.Success)
                    {
                        string solutionString = "";
                        foreach (KeyValuePair <string, int> pair in variableNameIndexMap)
                        {
                            solutionString += string.Format("{0} = {1}" + " ", pair.Key, xVector[pair.Value]);
                        }

                        return(solutionString);
                    }
                    else if (solverStatus == LinearEquationSolverStatus.IllConditioned)
                    {
                        mainStatusBarText = "Error - the system of equations is ill conditioned.";
                    }
                    else if (solverStatus == LinearEquationSolverStatus.Singular)
                    {
                        mainStatusBarText = "Error - the system of equations is singular.";
                    }
                }
                else if (numberOfEquations < variableNameIndexMap.Count)
                {
                    mainStatusBarText = string.Format("Only {0} equations is too few equations for {1} variables", numberOfEquations, variableNameIndexMap.Count);
                }
                else if (numberOfEquations > variableNameIndexMap.Count)
                {
                    mainStatusBarText = string.Format("{0} equations is too many equations for only {1} variables", numberOfEquations, variableNameIndexMap.Count);
                }
            }
            else
            {
                // An error occurred. Report the error in the status bar.
                mainStatusBarText = LinearEquationParserStatusInterpreter.GetStatusString(parserStatus);
            }

            return(mainStatusBarText);
        }
Пример #58
0
 public void UnloadData()
 {
     Data = null;
 }
Пример #59
0
        private void LoadAllFolders()
        {
            MFolders = new SparseArray <FolderModel>();
            string[] folders = FileList();
            foreach (string folderFileName in folders)
            {
                System.IO.FileStream @in = null;
                try
                {
                    if (folderFileName.StartsWith("folder", StringComparison.Ordinal))
                    {
                        FolderModel folder = new FolderModel();
                        folder.Id = int.Parse(folderFileName.Substring("folder".Length));

                        @in = (System.IO.FileStream)OpenFileInput(folderFileName);
                        System.IO.MemoryStream bos = new System.IO.MemoryStream();
                        byte[] b = new byte[1024];
                        int    bytesRead;
                        while ((bytesRead = @in.Read(b, 0, b.Length)) != -1)
                        {
                            bos.Write(b, 0, bytesRead);
                        }
                        byte[] bytes    = bos.ToArray();
                        string appNames = StringHelperClass.NewString((sbyte[])(Array)bytes);

                        int i = 0;
                        foreach (string appName in appNames.Split("\n", true))
                        {
                            if (i < 2)
                            {
                                // width and height
                                try
                                {
                                    if (i == 0)
                                    {
                                        folder.Width = int.Parse(appName);
                                    }
                                    else if (i == 1)
                                    {
                                        folder.Height = int.Parse(appName);
                                    }
                                }
                                catch (System.FormatException)
                                {
                                    string msg = "Please uninstall Floating Folders and reinstall it. The folder format has changed.";
                                    Log.Debug("FloatingFolder", msg);
                                    Toast.MakeText(this, msg, ToastLength.Short).Show();
                                    break;
                                }
                                i++;
                            }
                            else
                            {
                                if (appName.Length > 0)
                                {
                                    ComponentName name = ComponentName.UnflattenFromString(appName);
                                    try
                                    {
                                        ActivityInfo app = MPackageManager.GetActivityInfo(name, 0);
                                        folder.Apps.Add(app);
                                        MFolders.Put(folder.Id, folder);
                                    }
                                    catch (PackageManager.NameNotFoundException e)
                                    {
                                        System.Console.WriteLine(e.ToString());
                                        System.Console.Write(e.StackTrace);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (FileNotFoundException e)
                {
                    System.Console.WriteLine(e.ToString());
                    System.Console.Write(e.StackTrace);
                }
                catch (IOException e)
                {
                    System.Console.WriteLine(e.ToString());
                    System.Console.Write(e.StackTrace);
                }
                finally
                {
                    if (@in != null)
                    {
                        try
                        {
                            @in.Close();
                        }
                        catch (IOException e)
                        {
                            System.Console.WriteLine(e.ToString());
                            System.Console.Write(e.StackTrace);
                        }
                    }
                }
            }
        }
Пример #60
0
 public ViewHolder(Context context, View itemview) : base(itemview)
 {
     mContext     = context;
     mConvertView = itemview;
     mViews       = new SparseArray <View>();
 }