Exemplo n.º 1
0
 protected LogicalOptUnit(string id, int resolution, IntRange indexRange, IEnumerable<OptUnit> units)
     : base(id, ExtendOptUnits(units, resolution, indexRange))
 {
     Contract.Requires(!string.IsNullOrEmpty(id));
     Contract.Requires(resolution > 1);
     Contract.Requires(!indexRange.IsFixed && indexRange.MinValue >= 0);
 }
Exemplo n.º 2
0
 protected override int GetNext(IntRange fromRange, int soFar)
 {
     Contract.Requires(!fromRange.IsFixed);
     Contract.Requires(soFar >= 0);
     Contract.Ensures(fromRange.IsIn(Contract.Result<int>()));
     return 0;
 }
Exemplo n.º 3
0
        public void IsOverlappingTest( int min1, int max1, int min2, int max2, bool expectedResult )
        {
            IntRange range1 = new IntRange( min1, max1 );
            IntRange range2 = new IntRange( min2, max2 );

            Assert.AreEqual( expectedResult, range1.IsOverlapping( range2 ) );
        }
 public LogicalConnectionOptUnit(string id, int resolution, IntRange indexRange)
     : base(id, resolution, indexRange, CreateOptUnit())
 {
     Contract.Requires(!string.IsNullOrEmpty(id));
     Contract.Requires(resolution > 1);
     Contract.Requires(!indexRange.IsFixed && indexRange.MinValue >= 0);
 }
Exemplo n.º 5
0
 protected override void Build(BufferAllocator allocator, ConnectedLayerGroups connectedLayerGroups, NNInitParameters initPars)
 {
     var oclInitPars = (OpenCLNNInitParameters)initPars;
     CreateOpenCLContext(oclInitPars);
     inputBuffer = connectedLayerGroups.InputBuffer;
     outputBuffer = connectedLayerGroups.OutputBuffer;
 }
        public static void Run()
        {
            // ExStart:ConvertRangeOfDjVuPagesToSeparateImages
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DjVu();

            // Load a DjVu image
            using (DjvuImage image = (DjvuImage)Image.Load(dataDir + "Sample.djvu"))
            {
                // Create an instance of BmpOptions and Set BitsPerPixel for resultant images
                BmpOptions exportOptions = new BmpOptions();
                exportOptions.BitsPerPixel = 32;

                // Create an instance of IntRange and initialize it with range of pages to be exported
                IntRange range = new IntRange(0, 2);
                int counter = 0;
                foreach (var i in range.Range)
                {
                    // Save each page in separate file, as BMP do not support layering
                    exportOptions.MultiPageOptions = new DjvuMultiPageOptions(range.GetArrayOneItemFromIndex(counter));
                    image.Save(dataDir + string.Format("{0}_out.bmp", counter++), exportOptions);
                }
            }
            // ExEnd:ConvertRangeOfDjVuPagesToSeparateImages
        }
Exemplo n.º 7
0
 public void GetRandomIntOnDifferentThreadsGetsDifferentResults()
 {
     var numberToGenerate = 1000;
     var intRange = new IntRange(1, 10);
     var task1 = Task.Factory.StartNew(() =>
         {
             var taskResults = new List<int>();
             for (int i = 0; i < numberToGenerate; ++i)
             {
                 taskResults.Add(Randomizer<int>.Create(intRange));
             }
             return taskResults;
         },
         TaskCreationOptions.LongRunning
     );
     var task2 = Task.Factory.StartNew(() =>
         {
             var taskResults = new List<int>();
             for (int i = 0; i < numberToGenerate; ++i)
             {
                 taskResults.Add(Randomizer<int>.Create(intRange));
             }
             return taskResults;
         },
         TaskCreationOptions.LongRunning
     );
     var results = Task.WhenAll(task1, task2).Result;
     var firstResults = results[0].Sum();
     var secondResults = results[1].Sum();
     Assert.NotEqual(firstResults, secondResults);
 }
    public static double Calculate(ISymbolicTimeSeriesPrognosisExpressionTreeInterpreter interpreter, ISymbolicExpressionTree solution, double lowerEstimationLimit, double upperEstimationLimit, ITimeSeriesPrognosisProblemData problemData, IEnumerable<int> rows, IntRange evaluationPartition, int horizon, bool applyLinearScaling) {
      var horizions = rows.Select(r => Math.Min(horizon, evaluationPartition.End - r));
      IEnumerable<double> targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows.Zip(horizions, Enumerable.Range).SelectMany(r => r));
      IEnumerable<double> estimatedValues = interpreter.GetSymbolicExpressionTreeValues(solution, problemData.Dataset, rows, horizions).SelectMany(x => x);
      OnlineCalculatorError errorState;

      double mse;
      if (applyLinearScaling && horizon == 1) { //perform normal evaluation and afterwards scale the solution and calculate the fitness value        
        var mseCalculator = new OnlineMeanSquaredErrorCalculator();
        CalculateWithScaling(targetValues, estimatedValues, lowerEstimationLimit, upperEstimationLimit, mseCalculator, problemData.Dataset.Rows * horizon);
        errorState = mseCalculator.ErrorState;
        mse = mseCalculator.MeanSquaredError;
      } else if (applyLinearScaling) { //first create model to perform linear scaling and afterwards calculate fitness for the scaled model
        var model = new SymbolicTimeSeriesPrognosisModel((ISymbolicExpressionTree)solution.Clone(), interpreter, lowerEstimationLimit, upperEstimationLimit);
        model.Scale(problemData);
        var scaledSolution = model.SymbolicExpressionTree;
        estimatedValues = interpreter.GetSymbolicExpressionTreeValues(scaledSolution, problemData.Dataset, rows, horizions).SelectMany(x => x);
        var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
        mse = OnlineMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
      } else {
        var boundedEstimatedValues = estimatedValues.LimitToRange(lowerEstimationLimit, upperEstimationLimit);
        mse = OnlineMeanSquaredErrorCalculator.Calculate(targetValues, boundedEstimatedValues, out errorState);
      }

      if (errorState != OnlineCalculatorError.None) return Double.NaN;
      else return mse;
    }
Exemplo n.º 9
0
        public void ToRangeTest( int iMin, int iMax, float fMin, float fMax )
        {
            IntRange iRange = new IntRange( iMin, iMax );
            Range range = iRange;

            Assert.AreEqual( fMin, range.Min );
            Assert.AreEqual( fMax, range.Max );
        }
Exemplo n.º 10
0
 internal static unsafe double AverageDist(float* valueBuffer, IntRange errorBuffer)
 {
     double s = errorBuffer.Size;
     if (s == 0.0) return 0.0;
     double v = 0.0f;
     for (int i = errorBuffer.MinValue; i <= errorBuffer.MaxValue; i++) v += (float)Math.Pow(valueBuffer[i] * 0.5, 2.0);
     return v / s;
 }
Exemplo n.º 11
0
 internal static unsafe double Average(float* valueBuffer, IntRange errorBuffer)
 {
     double s = errorBuffer.Size;
     if (s == 0.0) return 0.0;
     double v = 0.0f;
     for (int i = errorBuffer.MinValue; i <= errorBuffer.MaxValue; i++) v += valueBuffer[i];
     return v / s;
 }
Exemplo n.º 12
0
        internal static void Zero(float[] valueBuffer, IntRange range)
        {
            Contract.Requires(valueBuffer != null);
            Contract.Requires(valueBuffer.Length >= range.MinValue);
            Contract.Requires(valueBuffer.Length >= range.MaxValue);

            Array.Clear(valueBuffer, range.MinValue, range.Size);
        }
Exemplo n.º 13
0
 ISet<int> ISelectionAlgorithm.Select(IntRange fromRange, int count)
 {
     Contract.Requires(!fromRange.IsFixed);
     Contract.Requires(count > 0 && fromRange.Size >= count);
     Contract.Ensures(Contract.Result<ISet<int>>() != null);
     Contract.Ensures(Contract.Result<ISet<int>>().Count == count);
     return null;
 }
Exemplo n.º 14
0
	// This is an overload of the SetupRoom function and has a corridor parameter that represents the corridor entering the room.
	public void SetupRoom (IntRange widthRange, IntRange heightRange, int columns, int rows, Corridor corridor, bool hasKey)
	{
		this.hasKey = hasKey;

		// Set the entering corridor direction.
		enteringCorridor = corridor.direction;

		// Set random values for width and height.
		roomWidth = widthRange.Random;
		roomHeight = heightRange.Random;

		//set the location that the key will spawn in in the room.
		keyLocation.x = widthRange.Random;
		keyLocation.y = heightRange.Random;


		switch (corridor.direction)
		{
		// If the corridor entering this room is going north...
		case Direction.North:
			// ... the height of the room mustn't go beyond the board so it must be clamped based
			// on the height of the board (rows) and the end of corridor that leads to the room.
			roomHeight = Mathf.Clamp(roomHeight, 1, rows - corridor.EndPositionY);

			// The y coordinate of the room must be at the end of the corridor (since the corridor leads to the bottom of the room).
			yPos = corridor.EndPositionY;

			// The x coordinate can be random but the left-most possibility is no further than the width
			// and the right-most possibility is that the end of the corridor is at the position of the room.
			xPos = Random.Range (corridor.EndPositionX - roomWidth + 1, corridor.EndPositionX);

			// This must be clamped to ensure that the room doesn't go off the board.
			xPos = Mathf.Clamp (xPos, 0, columns - roomWidth);
			break;
		case Direction.East:
			roomWidth = Mathf.Clamp(roomWidth, 1, columns - corridor.EndPositionX);
			xPos = corridor.EndPositionX;

			yPos = Random.Range (corridor.EndPositionY - roomHeight + 1, corridor.EndPositionY);
			yPos = Mathf.Clamp (yPos, 0, rows - roomHeight);
			break;
		case Direction.South:
			roomHeight = Mathf.Clamp (roomHeight, 1, corridor.EndPositionY);
			yPos = corridor.EndPositionY - roomHeight + 1;

			xPos = Random.Range (corridor.EndPositionX - roomWidth + 1, corridor.EndPositionX);
			xPos = Mathf.Clamp (xPos, 0, columns - roomWidth);
			break;
		case Direction.West:
			roomWidth = Mathf.Clamp (roomWidth, 1, corridor.EndPositionX);
			xPos = corridor.EndPositionX - roomWidth + 1;

			yPos = Random.Range (corridor.EndPositionY - roomHeight + 1, corridor.EndPositionY);
			yPos = Mathf.Clamp (yPos, 0, rows - roomHeight);
			break;
		}
	}
Exemplo n.º 15
0
    public int yPos; //y coordinate lower left tile of the room

    #endregion Fields

    #region Methods

    //setUp the first room
    public void SetUpRoom(IntRange widthRange, IntRange heightRange, int columns, int rows)
    {
        roomWidth = widthRange.Random;
        roomHeight = heightRange.Random;

        //set the x and y coordinates so that the first room is in the middle of the board
        xPos = Mathf.RoundToInt(columns / 2f - roomWidth / 2);
        yPos = Mathf.RoundToInt(rows / 2f - roomWidth / 2);
    }
Exemplo n.º 16
0
 public LogicGateOptUnit(string id, int resolution, IntRange indexRange, ISet<LogicalOperation> operations)
     : base(id, resolution, IntRange.CreateInclusive(1, indexRange.MaxValue), CreateOptUnit(resolution, operations))
 {
     Contract.Requires(!string.IsNullOrEmpty(id));
     Contract.Requires(resolution > 1);
     Contract.Requires(!indexRange.IsFixed && indexRange.MinValue >= 0);
     Contract.Requires(operations != null);
     Contract.Requires(operations.Count > 0);
 }
Exemplo n.º 17
0
        public void EqualityOperatorTest( int min1, int max1, int min2, int max2, bool areEqual )
        {
            IntRange range1 = new IntRange( min1, max1 );
            IntRange range2 = new IntRange( min2, max2 );

            Assert.AreEqual( range1.Equals( range2 ), areEqual );
            Assert.AreEqual( range1 == range2, areEqual );
            Assert.AreEqual( range1 != range2, !areEqual );
        }
Exemplo n.º 18
0
	// This is used for the first room.  It does not have a Corridor parameter since there are no corridors yet.
	public void SetupRoom (IntRange widthRange, IntRange heightRange, int columns, int rows)
	{
		// Set a random width and height.
		roomWidth = widthRange.Random;
		roomHeight = heightRange.Random;

		// Set the x and y coordinates so the room is roughly in the middle of the board.
		xPos = Mathf.RoundToInt(columns / 2f - roomWidth / 2f);
		yPos = Mathf.RoundToInt(rows / 2f - roomHeight / 2f);
	}
Exemplo n.º 19
0
        internal void Push(NeuralComputationContext context, IntRange errors)
        {
            Contract.Requires(context != null);

            IncIdx(context);

            var v = errorVectors[context.ErrorVectorStack_Index];
            network.CopyBuffer(context, errors, v);
            context.ErrorVectorStack_HasVectors[context.ErrorVectorStack_Index] = true;
        }
        public void enumerable_collection_has_expected_members()
        {
            var range = new IntRange(1, 5).ToArray();

            Assert.AreEqual(1, range[0]);
            Assert.AreEqual(2, range[1]);
            Assert.AreEqual(3, range[2]);
            Assert.AreEqual(4, range[3]);
            Assert.AreEqual(5, range[4]);
        }
Exemplo n.º 21
0
        public InputValueAccess(int inputSize, int inputBufferBeginIndex, int weightBufferBeginIndex, IntRange[] innerItarationInputValueStack)
        {
            Contract.Requires(inputSize > 0);
            Contract.Requires(inputBufferBeginIndex >= 0);
            Contract.Requires(weightBufferBeginIndex >= 0);

            this.inputSize = inputSize;
            this.inputBufferBeginIndex = inputBufferBeginIndex;
            this.weightBufferBeginIndex = weightBufferBeginIndex;
            this.innerItarationInputValueStack = innerItarationInputValueStack;
        }
Exemplo n.º 22
0
 public void SetupRoom(IntRange widthRange, IntRange heightRange, int columns, int rows)
 {
     roomWidth = widthRange.Random;
     roomHeight = heightRange.Random;
     
     Debug.Log(Mathf.RoundToInt(Mathf.RoundToInt(columns / 2f - roomWidth / 2f)));
     Debug.Log(Mathf.RoundToInt((rows / 2f - roomHeight / 2f)));
     
     xPos = Mathf.RoundToInt(columns / 2f - roomWidth / 2f);
     yPos = Mathf.RoundToInt(rows / 2f - roomHeight / 2f);
 }
 protected override int GetNext(IntRange fromRange, int soFar)
 {
     if (Direction == SelectionDirection.FromTop)
     {
         return fromRange.MinValue + soFar;
     }
     else
     {
         return fromRange.MaxValue + soFar;
     }
 }
        protected internal override unsafe void SetErrors(float* valueBuffer, IntRange errors)
        {
            Debug.Assert(OutputErrorBuffer.HasValue);
            Debug.Assert(OutputErrorBuffer.Value.Size == errors.Size);

            var eb = OutputErrorBuffer.Value;
            int ebSize = eb.Size;
            for (int i = 0; i < ebSize; i++)
            {
                valueBuffer[eb.MinValue + i] = valueBuffer[errors.MinValue + i];
            }
        } 
        public ISet<int> Select(IntRange fromRange, int count)
        {
            int size = TournamentSize;
            if (size < count) size = count;

            var arena = new SortedSet<int>();
            while (arena.Count != size)
            {
                arena.Add(fromRange.PickRandomValue());
            }

            return new HashSet<int>(arena.Take(count));
        }
Exemplo n.º 26
0
        private static IEnumerable<OptUnit> GetOptUnits(int resolution, IntRange indexRange, ISet<LogicalOperation> operations, bool nullAllowed)
        {
            Contract.Requires(resolution > 1);
            Contract.Requires(!indexRange.IsFixed && indexRange.MinValue >= 0);
            Contract.Requires(operations != null);
            Contract.Requires(operations.Count > 0);

            var units = new LinkedList<OptUnit>();
            if (nullAllowed) units.AddLast(new NullOptUnit(NullID));
            units.AddLast(new LogicalConnectionOptUnit(ConnectionID, resolution, indexRange));
            units.AddLast(new LogicGateOptUnit(GateID, resolution, indexRange, operations));
            return units;
        }
Exemplo n.º 27
0
 unsafe public void ReadArray(NeuralComputationContext context, IntRange range, float[] values)
 {
     int len = values.Length;
     int begin = range.MinValue;
     var valueBuffer = GetValueBuff(context);
     fixed (float* pValues = values, pValueBuffer = valueBuffer)
     {
         for (int i = 0; i < len; i++)
         {
             pValues[i] = pValueBuffer[begin + i];
         }
     }
 }
Exemplo n.º 28
0
 unsafe public void WriteVector(NeuralComputationContext context, IntRange range, BufferedVector<float> values)
 {
     int len = values.Length;
     int begin = range.MinValue;
     var valueBuffer = GetValueBuff(context);
     fixed (float* pValues = GetValueArray(values), pValueBuffer = valueBuffer)
     {
         for (int i = 0; i < len; i++)
         {
             pValueBuffer[begin + i] = pValues[i];
         }
     }
 }
Exemplo n.º 29
0
    public Direction enteringCorridor;    // The direction of the corridor that is entering this room.


    // This is used for the first room.  It does not have a Corridor parameter since there are no corridors yet.
    public void SetupRoom(IntRange widthRange, IntRange heightRange, int columns, int rows)
    {
        // Set a random width and height.
        roomWidth = widthRange.Random;
        roomHeight = heightRange.Random;

        // Set the x and y coordinates so the room is roughly in the middle of the board.
        //xPos = Mathf.RoundToInt(roomWidth / 2f);
        //yPos = Mathf.RoundToInt(rows / 2f - roomHeight / 2f);
		//The X and Y position of the first room should be in a set position since the hand crafted hub is stationary.
		xPos = 0;
		yPos = columns/2;
    }
        protected override int GetNext(IntRange fromRange, int soFar)
        {
            double value = Generate(); // Middle: 0.0
            if (value > 1.0) value = 1.0; else if (value < -1.0) value = -1.0; // Range: -1.0 .. 1.0, Middle: 0.0
            if (value < 0.0) value = -value; // Range: 0.0 .. 1.0, Highest: 0.0
            if (Direction == SelectionDirection.FromBottom) value = (1.0 - value); // Range: 0.0 .. 1.0, Highest: 1.0

            double min = fromRange.MinValue;
            double max = fromRange.MaxValue;
            double d = max - min;
            int result = (int)Math.Round(d * value + min);
            return result;
        }
Exemplo n.º 31
0
        public void TakeDamageFromRain()
        {
            if (pawn == null)
            {
                ULog.Error("CompFireStarter parent is not pawn");
                return;
            }
            IEnumerable <BodyPartRecord> notMissingParts = pawn.health.hediffSet.GetNotMissingParts();

            if (notMissingParts.Count() > 0)
            {
                List <BodyPartRecord> parts = (from b in notMissingParts where b.coverageAbs > 0 && !pawn.health.hediffSet.PartIsMissing(b) select b).ToList();
                int rand = new IntRange(0, parts.Count() - 1).RandomInRange;
                if (rand < parts.Count())
                {
                    BodyPartRecord part = parts.ElementAt(rand);
                    if (part != null)
                    {
                        pawn.TakeDamage(new DamageInfo(Props.rainDamage, damageAmt, 0f, hitPart: parts.ElementAt(rand)));
                    }
                }
            }
        }
Exemplo n.º 32
0
        public override bool DrawOption(Rect rect)
        {
            bool      changed = false;
            WidgetRow row     = new WidgetRow(rect.x, rect.y);

            row.Label("TD.AnythingXStepsNearbyMatches".Translate());
            if (row.ButtonText(any ? "TD.AnyOption".Translate() : "TD.AllOptions".Translate()))
            {
                any     = !any;
                changed = true;
            }

            IntRange slider = new IntRange(0, range);

            rect.xMin = row.FinalX;
            Widgets.IntRange(rect, id, ref slider, max: 10);
            if (range != slider.max)
            {
                range   = slider.max;
                changed = true;
            }
            return(changed);
        }
        public static void Run()
        {
            Console.WriteLine("Running example ConvertDjVuToPDF");
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DjVu();

            // Load a DjVu image
            using (DjvuImage image = (DjvuImage)Image.Load(dataDir + "Sample.djvu"))
            {
                // Create an instance of PdfOptions and Initialize the metadata for Pdf document
                PdfOptions exportOptions = new PdfOptions();
                exportOptions.PdfDocumentInfo = new PdfDocumentInfo();

                // Create an instance of IntRange and initialize it with the range of DjVu pages to be exported
                IntRange range = new IntRange(0, 5); //Export first 5 pages

                // Initialize an instance of DjvuMultiPageOptions with range of DjVu pages to be exported and Save the result in PDF format
                exportOptions.MultiPageOptions = new DjvuMultiPageOptions(range);
                image.Save(dataDir + "ConvertDjVuToPDFFormat_out.pdf", exportOptions);
            }

            Console.WriteLine("Finished example ConvertDjVuToPDF");
        }
Exemplo n.º 34
0
        protected int RandomCountOf(ThingDef def)
        {
            IntRange intRange = countRange;

            if (customCountRanges != null)
            {
                for (int i = 0; i < customCountRanges.Count; i++)
                {
                    if (customCountRanges[i].thingDef == def)
                    {
                        intRange = customCountRanges[i].countRange;
                        break;
                    }
                }
            }
            if (intRange.max <= 0 && totalPriceRange.max <= 0f)
            {
                return(0);
            }
            if (intRange.max > 0 && totalPriceRange.max <= 0f)
            {
                return(intRange.RandomInRange);
            }
            if (intRange.max <= 0 && totalPriceRange.max > 0f)
            {
                return(Mathf.RoundToInt(totalPriceRange.RandomInRange / def.BaseMarketValue));
            }
            int num = 0;
            int randomInRange;

            do
            {
                randomInRange = intRange.RandomInRange;
                num++;
            }while (num <= 100 && !totalPriceRange.Includes((float)randomInRange * def.BaseMarketValue));
            return(randomInRange);
        }
Exemplo n.º 35
0
    public void SetupBlock(IntRange widthRange, IntRange heightRange, int columns, int rows, Block block)
    {
        previousBlock = block;

        // Set random values for width and height.
        width  = widthRange.Random;
        height = heightRange.Random;

        // Position of the block should be dependant on the shape of previous block.
        shape = (Shape)(int)Random.Range(0, 5);

        while (shape == previousBlock.shape)
        {
            shape = (Shape)(int)Random.Range(0, 5);
        }

        xPos = previousBlock.xPos;
        yPos = previousBlock.yPos + previousBlock.height;

        // fixing positioning issues if previous shape was right turn
        if (previousBlock.shape == Shape.RightTurn)
        {
            if (shape != Shape.LeftTurn)
            {
                xPos = previousBlock.xPos + previousBlock.width / 2;
            }
        }

        //fixing positioning issues if this shape is left turn
        if (shape == Shape.LeftTurn)
        {
            if (previousBlock.shape != Shape.RightTurn)
            {
                xPos = previousBlock.xPos - previousBlock.width / 2;
            }
        }
    }
Exemplo n.º 36
0
        public void Import(IDataAnalysisProblemData problemData)
        {
            Dataset dataset = (Dataset)problemData.Dataset;

            variableNames  = new List <string>(problemData.Dataset.VariableNames);
            InputVariables = new List <string>(problemData.AllowedInputVariables);
            TargetVariable = (problemData is IRegressionProblemData) ? ((IRegressionProblemData)problemData).TargetVariable
        : (problemData is IClassificationProblemData) ? ((IClassificationProblemData)problemData).TargetVariable
          : null;

            int columnIndex = 0;

            variableValues = new List <IList>();
            foreach (var variableName in problemData.Dataset.VariableNames)
            {
                if (dataset.VariableHasType <double>(variableName))
                {
                    variableValues.Insert(columnIndex, dataset.GetDoubleValues(variableName).ToList());
                }
                else if (dataset.VariableHasType <string>(variableName))
                {
                    variableValues.Insert(columnIndex, dataset.GetStringValues(variableName).ToList());
                }
                else if (dataset.VariableHasType <DateTime>(variableName))
                {
                    variableValues.Insert(columnIndex, dataset.GetDateTimeValues(variableName).ToList());
                }
                else
                {
                    throw new ArgumentException("The datatype of column " + variableName + " must be of type double, string or DateTime");
                }
                ++columnIndex;
            }

            TrainingPartition = new IntRange(problemData.TrainingPartition.Start, problemData.TrainingPartition.End);
            TestPartition     = new IntRange(problemData.TestPartition.Start, problemData.TestPartition.End);
        }
Exemplo n.º 37
0
        public override void Generate(Map map, GenStepParams parms)
        {
            if (!this.allowInWaterBiome && map.TileInfo.WaterCovered)
            {
                return;
            }
            int      arg_AA_0 = base.CalculateFinalCount(map);
            IntRange one;

            if (this.thingDef.ingestible != null && this.thingDef.ingestible.IsMeal && this.thingDef.stackLimit <= 10)
            {
                one = IntRange.one;
            }
            else if (this.thingDef.stackLimit > 5)
            {
                one = new IntRange(Mathf.RoundToInt((float)this.thingDef.stackLimit * 0.5f), this.thingDef.stackLimit);
            }
            else
            {
                one = new IntRange(this.thingDef.stackLimit, this.thingDef.stackLimit);
            }
            List <int> list = GenStep_ScatterThings.CountDividedIntoStacks(arg_AA_0, one);

            for (int i = 0; i < list.Count; i++)
            {
                IntVec3 intVec;
                if (!this.TryFindScatterCell(map, out intVec))
                {
                    return;
                }
                this.ScatterAt(intVec, map, parms, list[i]);
                this.usedSpots.Add(intVec);
            }
            this.usedSpots.Clear();
            this.clusterCenter = IntVec3.Invalid;
            this.leftInCluster = 0;
        }
Exemplo n.º 38
0
        private static List <CircleDef> GenNestedCircles(CircleDef starterCircle, List <CircleDef> circles, int i = 0)
        {
            int radDist = starterCircle.Radius;

            if (i < 3)
            {
                IntRange additions  = new IntRange((int)(radDist * 1.3), (int)(radDist * 3));
                IntRange sizeWobble = new IntRange(-5, 5);

                for (int j = 0; j < 4 - i; j++)
                {
                    IntVec3 newCenter = starterCircle.Center;
                    if (Rand.Bool)
                    {
                        newCenter.x += additions.RandomInRange;
                    }
                    else
                    {
                        newCenter.x -= additions.RandomInRange;
                    }
                    if (Rand.Bool)
                    {
                        newCenter.z += additions.RandomInRange;
                    }
                    else
                    {
                        newCenter.z -= additions.RandomInRange;
                    }

                    CircleDef newCircle = new CircleDef(newCenter, (int)(sizeWobble.RandomInRange + radDist * 0.65));
                    circles.Add(newCircle);
                    circles.Concat(GenNestedCircles(newCircle, circles, i + 1));
                }
            }

            return(circles);
        }
Exemplo n.º 39
0
 static bool Prefix(ref Skyfaller __instance, Map map, bool respawningAfterLoad, ref int ___ticksToImpactMax)
 {
     BaseSpawnSetup(__instance, map, respawningAfterLoad);
     if (respawningAfterLoad)
     {
         return(false);
     }
     __instance.ticksToImpact = ___ticksToImpactMax = new IntRange(120, 200).RandomInRange / RefcellRespeedConfig.currentTimeMultiplier;
     if (__instance.def.skyfaller.MakesShrapnel)
     {
         float num = GenMath.PositiveMod(__instance.shrapnelDirection, 360f);
         __instance.angle = (double)num >= 270.0 || (double)num < 90.0 ? Rand.Range(-33f, 0.0f) : Rand.Range(0.0f, 33f);
     }
     else
     {
         __instance.angle = __instance.def.skyfaller.angleCurve == null ? -33.7f : __instance.def.skyfaller.angleCurve.Evaluate(0.0f);
     }
     if (!__instance.def.rotatable || !__instance.innerContainer.Any)
     {
         return(false);
     }
     __instance.Rotation = __instance.innerContainer[0].Rotation;
     return(false);
 }
Exemplo n.º 40
0
        private double computeInfoDiscrete(double[][] input, int[] output,
            int attributeIndex, out int[][] partitions)
        {
            // Compute the information gain obtained by using
            // this current attribute as the next decision node.
            double info = 0;

            IntRange valueRange = inputRanges[attributeIndex];
            partitions = new int[valueRange.Length + 1][];


            // For each possible value of the attribute
            for (int i = 0; i < partitions.Length; i++)
            {
                int value = valueRange.Min + i;

                
                double e = 699;

                info += ((double)e / output.Length) * e;
            }

            return info;
        }
Exemplo n.º 41
0
        protected override bool TryExecuteWorker(IncidentParms parms)
        {
            Map      map      = (Map)parms.target;
            CellRect cellRect = CellRect.WholeMap(map).ContractedBy(30);

            if (cellRect.IsEmpty)
            {
                cellRect = CellRect.WholeMap(map);
            }
            IntRange devils        = new IntRange(1, 5);
            int      randomInRange = devils.RandomInRange;

            for (int i = 0; i < randomInRange; i++)
            {
                IntVec3 loc;
                if (!CellFinder.TryFindRandomCellInsideWith(cellRect, (IntVec3 x) => this.CanSpawnDustDevilAt(x, map), out loc))
                {
                    return(false);
                }
                DustDevil t = (DustDevil)GenSpawn.Spawn(ThingDefOf.TKKN_DustDevil, loc, map);
                base.SendStandardLetter(t);
            }
            return(true);
        }
Exemplo n.º 42
0
        /// <summary>
        /// Creates the rooms in the map
        /// </summary>
        protected virtual void CreateRooms()
        {
            Rooms = new Room[NumRooms.Random];
            int attempts = 3;

            for (int i = 0; i < Rooms.Length; i++)
            {
                int cell = Random.Range(0, Cells.Length - 1);
                RoomWidth  = new IntRange(RoomMinWidth, CellSizeW - 1);
                RoomHeight = new IntRange(RoomMinHeight, CellSizeH - 1);

                if (Cells[cell].Used && attempts > 0)
                {
                    attempts--;
                    i--;
                    continue;
                }

                Rooms[i] = new Room();
                Rooms[i].SetupRoom(RoomWidth, RoomHeight, Cells[cell].YPos, Cells[cell].XPos);
                Cells[cell].Used = true;
                attempts         = 3;
            }
        }
Exemplo n.º 43
0
        private static DiaOption CreateAcceptOption(Pawn refugee, IntVec3 spawnSpot, Map map, Faction enemyFac)
        {
            DiaOption diaOption = new DiaOption("RefugeeChasedInitial_Accept".Translate());

            diaOption.action = delegate
            {
                GenSpawn.Spawn(refugee, spawnSpot, map);
                refugee.SetFaction(Faction.OfPlayer, null);
                Find.CameraDriver.JumpToVisibleMapLoc(spawnSpot);
                IncidentParms incidentParms = StorytellerUtility.DefaultParmsNow(Find.Storyteller.def, IncidentCategory.ThreatBig, map);
                incidentParms.forced          = true;
                incidentParms.faction         = enemyFac;
                incidentParms.raidStrategy    = RaidStrategyDefOf.ImmediateAttack;
                incidentParms.raidArrivalMode = PawnsArriveMode.EdgeWalkIn;
                incidentParms.spawnCenter     = spawnSpot;
                incidentParms.points         *= 1.35f;

                IntRange       raidDelay = (IntRange)typeof(IncidentWorker_RefugeeChased).GetField("RaidDelay", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                QueuedIncident qi        = new QueuedIncident(new FiringIncident(IncidentDefOf.RaidEnemy, null, incidentParms), Find.TickManager.TicksGame + raidDelay.RandomInRange);
                Find.Storyteller.incidentQueue.Add(qi);
            };
            diaOption.resolveTree = true;
            return(diaOption);
        }
    protected void BuyStockAtPowerLevel(EnumValue powerLevel, IntRange stockRange, FloatRange itemBudgetRange)
    {
        int   desiredCount  = stockRange.Random();
        int   currentCount  = GetTotalCount(powerLevel);
        float currentBudget = GetTotalCost(powerLevel);

        int   requiredStockCount = desiredCount - currentCount;
        float desiredTotalBudget = itemBudgetRange.Mean * requiredStockCount;

        if (requiredStockCount > 0)
        {
            float requiredStockBudget = desiredTotalBudget - currentBudget;

            if (requiredStockBudget > 0)
            {
                for (int i = 0; i < requiredStockCount; i++)
                {
                    EnumValue     itemPowerLevel     = EnumValue.Create(powerLevelEnum, powerLevelEnum[powerLevel]);
                    TSpecificItem randomSpecificItem = CreateRandomSpecificItem(itemPowerLevel, itemBudgetRange);
                    Add(randomSpecificItem);
                }
            }
        }
    }
Exemplo n.º 45
0
        /// <summary>
        /// Calculate conversion map.
        /// </summary>
        /// 
        /// <param name="inRange">Input range.</param>
        /// <param name="outRange">Output range.</param>
        /// <param name="map">Conversion map.</param>
        /// 
        private static void CalculateMap(IntRange inRange, IntRange outRange, byte[] map)
        {
            double k = 0, b = 0;

            if (inRange.Max != inRange.Min)
            {
                k = (double)(outRange.Max - outRange.Min) / (double)(inRange.Max - inRange.Min);
                b = (double)(outRange.Min) - k * inRange.Min;
            }

            for (int i = 0; i < 256; i++)
            {
                byte v = (byte)i;

                if (v >= inRange.Max)
                    v = (byte)outRange.Max;
                else if (v <= inRange.Min)
                    v = (byte)outRange.Min;
                else
                    v = (byte)(k * v + b);

                map[i] = v;
            }
        }
        private List <ThingStuffPairWithQuality> GeneratePossibleDefs(ThingSetMakerParams parms, out float totalNutrition)
        {
            IEnumerable <ThingDef> enumerable = this.AllowedThingDefs(parms);

            if (!enumerable.Any <ThingDef>())
            {
                totalNutrition = 0f;
                return(new List <ThingStuffPairWithQuality>());
            }
            IntRange?        countRange          = parms.countRange;
            IntRange         intRange            = (countRange == null) ? new IntRange(1, int.MaxValue) : countRange.Value;
            FloatRange?      totalNutritionRange = parms.totalNutritionRange;
            FloatRange       floatRange          = (totalNutritionRange == null) ? FloatRange.Zero : totalNutritionRange.Value;
            TechLevel?       techLevel           = parms.techLevel;
            TechLevel        techLevel2          = (techLevel == null) ? TechLevel.Undefined : techLevel.Value;
            float?           maxTotalMass        = parms.maxTotalMass;
            float            num = (maxTotalMass == null) ? float.MaxValue : maxTotalMass.Value;
            QualityGenerator?qualityGenerator  = parms.qualityGenerator;
            QualityGenerator qualityGenerator2 = (qualityGenerator == null) ? QualityGenerator.BaseGen : qualityGenerator.Value;

            totalNutrition = floatRange.RandomInRange;
            int numMeats                       = enumerable.Count((ThingDef x) => x.IsMeat);
            int numLeathers                    = enumerable.Count((ThingDef x) => x.IsLeather);
            Func <ThingDef, float> func        = (ThingDef x) => ThingSetMakerUtility.AdjustedBigCategoriesSelectionWeight(x, numMeats, numLeathers);
            IntRange countRange2               = intRange;
            float    totalValue                = totalNutrition;
            IEnumerable <ThingDef> allowed     = enumerable;
            TechLevel        techLevel3        = techLevel2;
            QualityGenerator qualityGenerator3 = qualityGenerator2;
            Func <ThingStuffPairWithQuality, float> getMinValue = (ThingStuffPairWithQuality x) => x.GetStatValue(StatDefOf.Nutrition);
            Func <ThingStuffPairWithQuality, float> getMaxValue = (ThingStuffPairWithQuality x) => x.GetStatValue(StatDefOf.Nutrition) * (float)x.thing.stackLimit;
            Func <ThingDef, float> weightSelector = func;
            float maxMass = num;

            return(ThingSetMakerByTotalStatUtility.GenerateDefsWithPossibleTotalValue(countRange2, totalValue, allowed, techLevel3, qualityGenerator3, getMinValue, getMaxValue, weightSelector, 100, maxMass));
        }
        public static void Run()
        {
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_DjVu();

            // Load a DjVu image
            using (DjvuImage image = (DjvuImage)Image.Load(dataDir + "Sample.djvu"))
            {
                // Create an instance of BmpOptions
                BmpOptions exportOptions = new BmpOptions();
                // Set BitsPerPixel for resultant images
                exportOptions.BitsPerPixel = 32;
                // Create an instance of IntRange and initialize it with range of pages to be exported
                IntRange range = new IntRange(0, 2); // Export first 2 pages

                int counter = 0;
                foreach (var i in range.Range)
                {
                    // Save each page in separate file, as BMP do not support layering
                    exportOptions.MultiPageOptions = new DjvuMultiPageOptions(range.GetArrayOneItemFromIndex(counter));
                    image.Save(dataDir + string.Format("{0}_out.bmp", counter++), exportOptions);
                }
            }
        }
Exemplo n.º 48
0
    public void SetupCorridor(Room room, IntRange length, IntRange roomWidth, IntRange roomHeight, int columns, int rows, bool firstCorridor)
    {
        // Set a random direction (a random index from 0 to 3, cast to Direction).
        direction = (Direction)Random.Range(0, 4);

        // Find the direction opposite to the one entering the room this corridor is leaving from.
        // Cast the previous corridor's direction to an int between 0 and 3 and add 2 (a number between 2 and 5).
        // Find the remainder when dividing by 4 (if 2 then 2, if 3 then 3, if 4 then 0, if 5 then 1).
        // Cast this number back to a direction.
        // Overall effect is if the direction was South then that is 2, becomes 4, remainder is 0, which is north.
        Direction oppositeDirection = (Direction)(((int)room.enteringCorridor + 2) % 4);

        // If this is noth the first corridor and the randomly selected direction is opposite to the previous corridor's direction...
        if (!firstCorridor && direction == oppositeDirection)
        {
            // Rotate the direction 90 degrees clockwise (North becomes East, East becomes South, etc).
            // This is a more broken down version of the opposite direction operation above but instead of adding 2 we're adding 1.
            // This means instead of rotating 180 (the opposite direction) we're rotating 90.
            int directionInt = (int)direction;
            directionInt++;
            directionInt = directionInt % 4;
            direction    = (Direction)directionInt;
        }

        // Set a random length.
        corridorLength = length.Random;

        // Create a cap for how long the length can be (this will be changed based on the direction and position).
        int maxLength = length.m_Max;

        switch (direction)
        {
        // If the choosen direction is North (up)...
        case Direction.North:
            // ... the starting position in the x axis can be random but within the width of the room.
            startXPos = Random.Range(room.xPos, room.xPos + room.roomWidth - 1);

            // The starting position in the y axis must be the top of the room.
            startYPos = room.yPos + room.roomHeight;

            // The maximum length the corridor can be is the height of the board (rows) but from the top of the room (y pos + height).
            maxLength = rows - startYPos - roomHeight.m_Min;
            break;

        case Direction.East:
            startXPos = room.xPos + room.roomWidth;
            startYPos = Random.Range(room.yPos, room.yPos + room.roomHeight - 1);
            maxLength = columns - startXPos - roomWidth.m_Min;
            break;

        case Direction.South:
            startXPos = Random.Range(room.xPos, room.xPos + room.roomWidth);
            startYPos = room.yPos;
            maxLength = startYPos - roomHeight.m_Min;
            break;

        case Direction.West:
            startXPos = room.xPos;
            startYPos = Random.Range(room.yPos, room.yPos + room.roomHeight);
            maxLength = startXPos - roomWidth.m_Min;
            break;
        }

        // We clamp the length of the corridor to make sure it doesn't go off the board.
        corridorLength = Mathf.Clamp(corridorLength, 1, maxLength);
    }
Exemplo n.º 49
0
 public static IntegerChromosome Of(IntRange range)
 {
     return(new IntegerChromosome(range.Min, range.Max));
 }
Exemplo n.º 50
0
 protected override void SetDefaults()
 {
     days    = IntRange.Create();
     percent = IntRange.Create();
 }
Exemplo n.º 51
0
 protected override void SetupFromSplitJsonString(string[] splitJsonString)
 {
     days    = IntRange.CreateFromJsonString(splitJsonString[0]);
     percent = IntRange.CreateFromJsonString(splitJsonString[1]);
 }
 private static bool Includes(IntRange i, int val)
 {
     return(val >= i.min && val <= i.max);
 }
Exemplo n.º 53
0
 ///<summary>Draws this OverlayIndicator chart for a specified time span.</summary>
 ///<param name="drawingContext">Provides methods for drawing lines and shapes on the price chart area.</param>
 ///<param name="visibleCandlesRange">Specifies the time span currently shown on the price chart area. The range of the candles currently visible on the price chart.</param>
 ///<param name="visibleCandlesExtremums">The maximal High and minimal Low of the candles in visibleCandlesRange.</param>
 ///<param name="candleWidth">The Width of candle of the price chart, in device-independent units.</param>
 ///<param name="gapBetweenCandles">The Gap between candles of the price chart, in device-independent units.</param>
 ///<param name="RenderHeight">The height of the price chart area, in device-independent units.</param>
 ///<remarks>
 ///This is an analog of the <see href="https://docs.microsoft.com/en-za/dotnet/api/system.windows.uielement.onrender?view=netframework-4.7.2">UIElement.OnRender()</see> method.
 ///Participates in rendering operations that are directed by the layout system. The rendering instructions for this indicator are not used directly when this method is invoked, and are instead preserved for later asynchronous use by layout and drawing.
 ///</remarks>
 public abstract void OnRender(DrawingContext drawingContext, IntRange visibleCandlesRange, CandleExtremums visibleCandlesExtremums,
                               double candleWidth, double gapBetweenCandles, double RenderHeight);
Exemplo n.º 54
0
 public static bool Contains(this IntRange range, float value)
 {
     return(value >= range.Min && value <= range.Max);
 }
Exemplo n.º 55
0
        private bool TryFindTile(out int tile)
        {
            IntRange prisonerRescueQuestSiteDistanceRange = SiteTuning.PrisonerRescueQuestSiteDistanceRange;

            return(TileFinder.TryFindNewSiteTile(out tile, prisonerRescueQuestSiteDistanceRange.min, prisonerRescueQuestSiteDistanceRange.max, false, false, -1));
        }
Exemplo n.º 56
0
    // This is an overload of the SetupRoom function and has a corridor parameter that represents the corridor entering the room.
    public void SetupRoom(IntRange widthRange, IntRange heightRange, int columns, int rows, Corridor corridor,
                          GameObject[] enemies, int numEnemyTypes, GameObject exit)
    {
        // Set the entering corridor direction.
        enteringCorridor = corridor.direction;

        // Set random values for width and height.
        roomWidth  = widthRange.Random;
        roomHeight = heightRange.Random;
        int numEnemies = Random.Range(0, 2);

        switch (corridor.direction)
        {
        // If the corridor entering this room is going north...
        case Direction.North:
            // ... the height of the room mustn't go beyond the board so it must be clamped based
            // on the height of the board (rows) and the end of corridor that leads to the room.
            roomHeight = Mathf.Clamp(roomHeight, 1, rows - corridor.EndPositionY);

            // The y coordinate of the room must be at the end of the corridor (since the corridor leads to the bottom of the room).
            yPos = corridor.EndPositionY;

            // The x coordinate can be random but the left-most possibility is no further than the width
            // and the right-most possibility is that the end of the corridor is at the position of the room.
            xPos = Random.Range(corridor.EndPositionX - roomWidth + 1, corridor.EndPositionX);

            // This must be clamped to ensure that the room doesn't go off the board.
            xPos = Mathf.Clamp(xPos, 0, columns - roomWidth);

            spawnEnemies(enemies, numEnemies, numEnemyTypes);
            spawnExit(exit);
            break;

        case Direction.East:
            roomWidth = Mathf.Clamp(roomWidth, 1, columns - corridor.EndPositionX);
            xPos      = corridor.EndPositionX;

            yPos = Random.Range(corridor.EndPositionY - roomHeight + 1, corridor.EndPositionY);
            yPos = Mathf.Clamp(yPos, 0, rows - roomHeight);

            spawnEnemies(enemies, numEnemies, numEnemyTypes);
            spawnExit(exit);
            break;

        case Direction.South:
            roomHeight = Mathf.Clamp(roomHeight, 1, corridor.EndPositionY);
            yPos       = corridor.EndPositionY - roomHeight + 1;

            xPos = Random.Range(corridor.EndPositionX - roomWidth + 1, corridor.EndPositionX);
            xPos = Mathf.Clamp(xPos, 0, columns - roomWidth);

            spawnEnemies(enemies, numEnemies, numEnemyTypes);
            spawnExit(exit);
            break;

        case Direction.West:
            roomWidth = Mathf.Clamp(roomWidth, 1, corridor.EndPositionX);
            xPos      = corridor.EndPositionX - roomWidth + 1;

            yPos = Random.Range(corridor.EndPositionY - roomHeight + 1, corridor.EndPositionY);
            yPos = Mathf.Clamp(yPos, 0, rows - roomHeight);

            spawnEnemies(enemies, numEnemies, numEnemyTypes);
            spawnExit(exit);
            break;
        }
    }
Exemplo n.º 57
0
 public static bool Includes(this IntRange range, float num)
 {
     return(num <= range.max && num >= range.max);
 }
Exemplo n.º 58
0
        /// <summary>
        ///   Gets the distribution range within a given percentile.
        /// </summary>
        ///
        /// <remarks>
        ///   If <c>0.25</c> is passed as the <paramref name="percentile"/> argument,
        ///   this function returns the same as the <see cref="Quartiles"/> function.
        /// </remarks>
        ///
        /// <param name="percentile">
        ///   The percentile at which the distribution ranges will be returned.</param>
        ///
        /// <value>A <see cref="DoubleRange"/> object containing the minimum value
        /// for the distribution value, and the third quartile (Q2) as the maximum.</value>
        ///
        DoubleRange IUnivariateDistribution.GetRange(double percentile)
        {
            IntRange range = GetRange(percentile);

            return(new DoubleRange(range.Min, range.Max));
        }
Exemplo n.º 59
0
 public InAgeRange()
 {
     this.label = "In age range:";
     this.range = new IntRange(20, 55);
 }
Exemplo n.º 60
0
 public static int Average(this IntRange range)
 {
     return((range.Min + range.Max) / 2);
 }