public void GenerateHaltonSequence() { #if UNITY_EDITOR HaltonSequenceData data = new HaltonSequenceData(3000); HaltonSequence seq = new HaltonSequence(); for (int i = 0; i < 3000; i++) { Vector3 value = seq.m_CurrentPos; while (value.x + value.z > 1f) { seq.Increment(); value = seq.m_CurrentPos; } data.xArray[i] = value.x; data.yArray[i] = value.z; seq.Increment(); } using (System.IO.MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, data); byte[] bytes = ms.ToArray(); File.WriteAllBytes("Assets/Tutorial/Pathfinding/Resources/HaltonSequence.bytes", bytes); } AssetDatabase.Refresh(); #endif }
private async Task <List <Element> > GenerateElements(Terrain terrain, Rect rect, MassiveGrassProfile profile, int haltonOffset) { var list = new List <Element>(); var terrainPos = terrain.transform.position; var terrainSize = terrain.terrainData.size.x; var terrainXZPos = new Vector2(terrainPos.x, terrainPos.z); var localRect = new Rect(rect.min - terrainXZPos, rect.size); var localNormalizedRect = new Rect(localRect.position / terrainSize, localRect.size / terrainSize); for (var i = 0; i < profile.AmountPerBlock; i++) { var haltonPos = new Vector2(HaltonSequence.Base2(i + haltonOffset), HaltonSequence.Base3(i + haltonOffset)); var normalizedPosition = localNormalizedRect.min + haltonPos * localNormalizedRect.size; var height = terrain.terrainData.GetInterpolatedHeight(normalizedPosition.x, normalizedPosition.y); var normal = terrain.terrainData.GetInterpolatedNormal(normalizedPosition.x, normalizedPosition.y); var position = haltonPos * rect.size + rect.min; list.Add( new Element( i, new Vector3(position.x, height, position.y), normalizedPosition, normal)); } return(list); }
public Vector2 Next() { index++; return(new Vector2( Range * HaltonSequence.Base2(index), Range * HaltonSequence.Base3(index))); }
private void OnEnable() { HaltonSequence.Warmup(); ParkAndMiller.Warmup(); SetupBounds(); RenderPipelineManager.beginCameraRendering += OnBeginRender; // for SRP }
public void GetElement_3DNonzeroIndex_ReturnsExpectedElement() { int index = 10; double[] expected = sequence3D[index]; double[] result = HaltonSequence.GetElement(3, index); Assert.That(result, Is.EqualTo(expected).Within(5E-6)); }
Matrix4x4 GetJitteredProjectionMatrix(Matrix4x4 origProj) { // The variance between 0 and the actual halton sequence values reveals noticeable // instability in Unity's shadow maps, so we avoid index 0. float jitterX = HaltonSequence.Get((taaFrameIndex & 1023) + 1, 2) - 0.5f; float jitterY = HaltonSequence.Get((taaFrameIndex & 1023) + 1, 3) - 0.5f; taaJitter = new Vector4(jitterX, jitterY, jitterX / camera.pixelWidth, jitterY / camera.pixelHeight); const int kMaxSampleCount = 8; if (++taaFrameIndex >= kMaxSampleCount) { taaFrameIndex = 0; } Matrix4x4 proj; if (camera.orthographic) { float vertical = camera.orthographicSize; float horizontal = vertical * camera.aspect; var offset = taaJitter; offset.x *= horizontal / (0.5f * camera.pixelWidth); offset.y *= vertical / (0.5f * camera.pixelHeight); float left = offset.x - horizontal; float right = offset.x + horizontal; float top = offset.y + vertical; float bottom = offset.y - vertical; proj = Matrix4x4.Ortho(left, right, bottom, top, camera.nearClipPlane, camera.farClipPlane); } else { var planes = origProj.decomposeProjection; float vertFov = Math.Abs(planes.top) + Math.Abs(planes.bottom); float horizFov = Math.Abs(planes.left) + Math.Abs(planes.right); var planeJitter = new Vector2(jitterX * horizFov / camera.pixelWidth, jitterY * vertFov / camera.pixelHeight); planes.left += planeJitter.x; planes.right += planeJitter.x; planes.top += planeJitter.y; planes.bottom += planeJitter.y; proj = Matrix4x4.Frustum(planes); } return(proj); }
public void TestHaltonSequence() { for (var m = 1; m <= 3; m++) { var r = HaltonSequence.Sequence(0, 10, m); Debug.Print(r[m].ToString(CultureInfo.InvariantCulture)); } var s = HaltonSequence.Sequence(10, 0, 2); Debug.Print(s[0].ToString(CultureInfo.InvariantCulture)); Debug.Print(s[1].ToString(CultureInfo.InvariantCulture)); }
public void HaltonGeneric_Impl_2D_Test() { var halton = new HaltonSequence(2); var seq = halton.GetSequence(); foreach (var item in seq.Zip(_seqBase3, Tuple.Create)) { Assert.AreEqual(item.Item1[1], item.Item2); } }
public Vector2 Sample(Vector2 maximum, Vector2 minimum = default) { var offset = minimum; var scale = maximum - minimum; var sample = new Vector2( HaltonSequence.Get(indexInSequence, horizontalRadix), HaltonSequence.Get(indexInSequence, verticalRadix) ); indexInSequence++; return((sample * scale) + offset); }
public void Next_3DNonzeroSeed_ReturnsExpectedElement() { int index = 6; double[] expected1 = sequence3D[index]; double[] expected2 = sequence3D[index + 1]; HaltonSequence halton = new HaltonSequence(3, index); var result1 = halton.Next(); var result2 = halton.Next(); Assert.That(result1, Is.EqualTo(expected1).Within(5E-6)); Assert.That(result2, Is.EqualTo(expected2).Within(5E-6)); }
private void PlaceObject() { TextAsset haltonSeq = Resources.Load <TextAsset>("HaltonSequence"); BinaryFormatter bf = new BinaryFormatter(); _haltonSequenceData = bf.Deserialize(new MemoryStream(haltonSeq.bytes)) as HaltonSequenceData; _haltonSeq = new HaltonSequence(); _prefab = Resources.Load <GameObject>("SimpleBuilding"); for (int i = 0; i < count; i++) { Vector3 pos = GetRandomPos(); Instantiate(_prefab, pos, Quaternion.identity, this.transform); } }
private Matrix4x4 GetJitteredProjectionMatrix(Matrix4x4 origProj, Camera UnityCamera) { float jitterX = HaltonSequence.Get((FrameIndex & 1023) + 1, 2) - 0.5f; float jitterY = HaltonSequence.Get((FrameIndex & 1023) + 1, 3) - 0.5f; TAAJitter = new float2(jitterX, jitterY); float4 taaJitter = new float4(jitterX, jitterY, jitterX / UnityCamera.pixelRect.size.x, jitterY / UnityCamera.pixelRect.size.y); if (++FrameIndex >= 8) { FrameIndex = 0; } Matrix4x4 proj; if (UnityCamera.orthographic) { float vertical = UnityCamera.orthographicSize; float horizontal = vertical * UnityCamera.aspect; var offset = taaJitter; offset.x *= horizontal / (0.5f * UnityCamera.pixelRect.size.x); offset.y *= vertical / (0.5f * UnityCamera.pixelRect.size.y); float left = offset.x - horizontal; float right = offset.x + horizontal; float top = offset.y + vertical; float bottom = offset.y - vertical; proj = Matrix4x4.Ortho(left, right, bottom, top, UnityCamera.nearClipPlane, UnityCamera.farClipPlane); } else { var planes = origProj.decomposeProjection; float vertFov = Math.Abs(planes.top) + Math.Abs(planes.bottom); float horizFov = Math.Abs(planes.left) + Math.Abs(planes.right); var planeJitter = new Vector2(jitterX * horizFov / UnityCamera.pixelRect.size.x, jitterY * vertFov / UnityCamera.pixelRect.size.y); planes.left += planeJitter.x; planes.right += planeJitter.x; planes.top += planeJitter.y; planes.bottom += planeJitter.y; proj = Matrix4x4.Frustum(planes); } return(proj); }
public void TestHalton() { for (var m = 1; m <= 3; m++) { int i; for (i = 0; i <= 10; i++) { var r = HaltonSequence.Halton(i, m); int j; for (j = 0; j < m; j++) { Debug.Print(r[j].ToString(CultureInfo.InvariantCulture)); } } } }
void Awake() { // Create random points int n = seed; points = new List <Vec3>(); switch (usedGenerator) { case Generator.Halton: for (int i = 0; i < pointNumber; i++) { // Random sparse distribution Vec3 temp = HaltonSequence.Halton2D(n, bases[0], bases[1]); points.Add(new Vec3(temp.X * boundaries[0] + transform.position.x, temp.Y * boundaries[1] + transform.position.y, transform.position.z)); n++; } break; case Generator.Poisson: RandGen.Init(seed); poissonGen = new PoissonDisk2D(minimalDistance, boundaries[0], boundaries[1], maxAttemp); poissonGen.BuildSample(pointNumber); foreach (Vec3 point in poissonGen) { points.Add(point); } break; default: throw new NotImplementedException(); } // Place camera var cam = Camera.main; cam.transform.position = new Vector3(boundaries[0] / 2.0f, boundaries[1] / 2.0f, -0.8f * Mathf.Max(boundaries)); }
// Use this for initialization void Awake() { colorsLength = colors.Length; int n = sequenceInit; points = new Vector3[pointNumber]; pointsObject = new GameObject[pointNumber]; for (int i = 0; i < points.Length; i++) { // Random sparse distribution points[i] = HaltonSequence.Halton2D(n, bases[0], bases[1]).AsVector3(); // Scale to boundaries and translate based on generator position points[i].x *= boundaries[0]; points[i].x += transform.position.x; points[i].y *= boundaries[1]; points[i].y += transform.position.y; points[i].z += transform.position.z; // Create a shape using points coordinates var newShape = Instantiate(shape); newShape.transform.SetParent(this.transform); newShape.transform.position = points[i]; newShape.transform.localScale = new Vector3(ShapeScale, ShapeScale, ShapeScale); // Random color newShape.GetComponent <MeshRenderer>().materials[0].color = colors[Random.Range(0, colorsLength)]; // Keep track of shape pointsObject[i] = newShape; n++; } // Place camera var cam = Camera.main; cam.transform.position = new Vector3(boundaries[0] / 2.0f, boundaries[1] / 2.0f, -0.8f * Mathf.Max(boundaries)); }
public bool AuxiliaryFunction(int index, out object output) { var approx = new ARMAModel(0, maxLag); // we should be able to get close with an MA var hlds = new HaltonSequence(maxLag); double bestError = double.MaxValue; var bestMAPolynomial = Vector <double> .Build.Dense(maxLag);//new Polynomial(maxLag); for (int i = 0; i < 200000; ++i) { var cube = hlds.GetNext(); // this is the MA part to try in the ARMA var curCube = approx.ParameterToCube(approx.Parameters); // el. 0=mu, el. 1=d, el. 2=sigma for (int j = 0; j < maxLag; ++j) { curCube[j + 3] = cube[j]; } approx.SetParameters(approx.CubeToParameter(curCube)); // now compare autocorrelation function (don't care about mean or sigma) var acf = approx.ComputeACF(maxLag, true); double error = 0; for (int j = 0; j < maxLag; ++j) { error += Math.Abs(acf[j + 1] - Rho(j)); } if (error < bestError) { bestError = error; bestMAPolynomial = approx.GetMAPolynomial(); } } approx.SetMAPolynomial(bestMAPolynomial); approx.Mu = Mu; output = approx; return(true); }
public void TestHaltonBase() { var b1 = new[] { 2, 3, 5 }; var b2 = new[] { 3, 10, 2 }; int i; int j; double[] r; var m = 3; for (j = 0; j < m; j++) { Debug.Print(b1[j].ToString(CultureInfo.InvariantCulture)); } for (i = 0; i <= 10; i++) { r = HaltonSequence.HaltonBase(i, m, b1); Debug.Print(i.ToString(CultureInfo.InvariantCulture)); for (j = 0; j < m; j++) { Debug.Print(r[j].ToString(CultureInfo.InvariantCulture)); } } for (j = 0; j < m; j++) { Debug.Print(b2[j].ToString(CultureInfo.InvariantCulture)); } for (i = 0; i <= 10; i++) { r = HaltonSequence.HaltonBase(i, m, b2); for (j = 0; j < m; j++) { Debug.Print(r[j].ToString(CultureInfo.InvariantCulture)); } } }
/// This function samples from parameter space using a Halton sequence and picks /// the model with best log-likelihood. /// Individual parameters are tagged as ParameterState.Locked, ParameterState.Free, or ParameterState.Consequential. /// Locked parameters are held at current values in optimization. /// Free parameters are optimized. /// Consequential parameters are computed as a function of other parameters and the data. public virtual void FitByMLE(int numIterationsLDS, int numIterationsOpt, double consistencyPenalty, Optimizer.OptimizationCallback optCallback) { thisAsMLEEstimable = this as IMLEEstimable; if (thisAsMLEEstimable == null) { throw new ApplicationException("MLE not supported for this model."); } int optDimension = NumParametersOfType(ParameterState.Free); int numConsequential = NumParametersOfType(ParameterState.Consequential); int numIterations = numIterationsLDS + numIterationsOpt; var trialParameterList = new Vector <double> [numIterationsLDS]; var trialCubeList = new Vector <double> [numIterationsLDS]; var hsequence = new HaltonSequence(optDimension); if (optDimension == 0) // then all parameters are either locked or consequential { Vector <double> tparms = Parameters; Parameters = ComputeConsequentialParameters(tparms); } else { thisAsMLEEstimable.CarryOutPreMLEComputations(); for (int i = 0; i < numIterationsLDS; ++i) { Vector <double> smallCube = hsequence.GetNext(); Vector <double> cube = CubeInsert(smallCube); trialParameterList[i] = thisAsMLEEstimable.CubeToParameter(cube); trialCubeList[i] = cube; } var logLikes = new double[numIterationsLDS]; //const bool multiThreaded = false; //if (multiThreaded) //{ // Parallel.For(0, numIterations, // i => // { // Vector tparms = trialParameterList[i]; // if (numConsequential > 0) // { // tparms = ComputeConsequentialParameters(tparms); // lock (trialParameterList) // trialParameterList[i] = tparms; // } // double ll = LogLikelihood(tparms); // if (optCallback != null) // lock (logLikes) // optCallback(tparms, ll, // (int)(i * 100 / numIterations), false); // lock (logLikes) // logLikes[i] = ll; // }); //} for (int i = 0; i < numIterationsLDS; ++i) { Vector <double> tparms = trialParameterList[i]; if (numConsequential > 0) { tparms = ComputeConsequentialParameters(tparms); trialParameterList[i] = tparms; } double ll = LogLikelihood(tparms, consistencyPenalty, false); logLikes[i] = ll; if (optCallback != null) { lock (logLikes) optCallback(tparms, ll, i * 100 / numIterations, false); } } // Step 1: Just take the best value. Array.Sort(logLikes, trialParameterList); Parameters = trialParameterList[numIterationsLDS - 1]; // Step 2: Take some of the top values and use them to create a simplex, then optimize // further in natural parameter space with the Nelder Mead algorithm. // Here we optimize in cube space, reflecting the cube when necessary to make parameters valid. var simplex = new List <Vector <double> >(); for (int i = 0; i <= optDimension; ++i) { simplex.Add( FreeParameters(thisAsMLEEstimable.ParameterToCube(trialParameterList[numIterationsLDS - 1 - i]))); } var nmOptimizer = new NelderMead { Callback = optCallback, StartIteration = numIterationsLDS }; currentPenalty = consistencyPenalty; nmOptimizer.Minimize(NegativeLogLikelihood, simplex, numIterationsOpt); Parameters = ComputeConsequentialParameters( thisAsMLEEstimable.CubeToParameter(CubeFix(CubeInsert(nmOptimizer.ArgMin)))); } LogLikelihood(null, 0.0, true); }
private async Task <List <Element> > GenerateElements(Terrain terrain, Rect rect, MassiveGrassProfile profile, int haltonOffset) { var context = SynchronizationContext.Current; var terrainPos = terrain.transform.position; var terrainSize = terrain.terrainData.size.x; var terrainXZPos = new Vector2(terrainPos.x, terrainPos.z); var localRect = new Rect(rect.min - terrainXZPos, rect.size); var localNormalizedRect = new Rect(localRect.position / terrainSize, localRect.size / terrainSize); var haltons = new Vector2[profile.AmountPerBlock]; var normalizedPositions = new Vector2[profile.AmountPerBlock]; var heights = new float[profile.AmountPerBlock]; var normals = new Vector3[profile.AmountPerBlock]; var list = new List <Element>(); var done = false; var range = Enumerable.Range(0, profile.AmountPerBlock).ToArray(); list.AddRange(range.Select(_ => default(Element))); await Task.Run(() => { for (var i = 0; i < profile.AmountPerBlock; i++) { haltons[i] = new Vector2( HaltonSequence.Base2(i + haltonOffset + profile.Seed), HaltonSequence.Base3(i + haltonOffset + profile.Seed)); normalizedPositions[i] = localNormalizedRect.min + haltons[i] * localNormalizedRect.size; } }); await Task.Run(async() => { context.Post(_ => { for (var i = 0; i < profile.AmountPerBlock; i++) { if (terrain == null) { break; } var normalizedPosition = normalizedPositions[i]; heights[i] = terrain.terrainData.GetInterpolatedHeight(normalizedPosition.x, normalizedPosition.y); normals[i] = terrain.terrainData.GetInterpolatedNormal(normalizedPosition.x, normalizedPosition.y); } done = true; }, null); }); while (!done) { await Task.Delay(1); } await Task.Run(() => { for (var i = 0; i < profile.AmountPerBlock; i++) { var haltonPos = haltons[i]; var position = haltonPos *rect.size + rect.min; var normalizedPosition = localNormalizedRect.min + haltons[i] * localNormalizedRect.size; list[i] = new Element( i, new Vector3(position.x, heights[i], position.y), normalizedPosition, normals[i]); } }); return(list); }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(HaltonSequence obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
public void TestHalton2() { //("Testing Halton sequences..."); double[] point; double tolerance = 1.0e-15; // testing "high" dimensionality int dimensionality = 2; int points = 100, i; for (i = 0; i < points; i++) { point = HaltonSequence.Halton(i, dimensionality); Assert.AreEqual(point.Length, dimensionality); } // testing first and second dimension (van der Corput sequence) double[] vanderCorputSequenceModuloTwo = { // first cycle (zero excluded) 0.50000, // second cycle 0.25000, 0.75000, // third cycle 0.12500, 0.62500, 0.37500, 0.87500, // fourth cycle 0.06250, 0.56250, 0.31250, 0.81250, 0.18750, 0.68750, 0.43750, 0.93750, // fifth cycle 0.03125, 0.53125, 0.28125, 0.78125, 0.15625, 0.65625, 0.40625, 0.90625, 0.09375, 0.59375, 0.34375, 0.84375, 0.21875, 0.71875, 0.46875, 0.96875, }; dimensionality = 1; points = (int)Math.Pow(2.0, 5) - 1; // five cycles for (i = 0; i < points; i++) { point = HaltonSequence.Halton(i, dimensionality); double error = Math.Abs(point[0] - vanderCorputSequenceModuloTwo[i]); if (error > tolerance) { Debug.Print(i + 1 + " draw (" + +point[0] + ") in 1-D Halton sequence is not in the " + "van der Corput sequence modulo two: " + "it should have been " + vanderCorputSequenceModuloTwo[i] + " (error = " + error + ")"); } } double[] vanderCorputSequenceModuloThree = { // first cycle (zero excluded) 1.0 / 3, 2.0 / 3, // second cycle 1.0 / 9, 4.0 / 9, 7.0 / 9, 2.0 / 9, 5.0 / 9, 8.0 / 9, // third cycle 1.0 / 27, 10.0 / 27, 19.0 / 27, 4.0 / 27, 13.0 / 27, 22.0 / 27, 7.0 / 27, 16.0 / 27, 25.0 / 27, 2.0 / 27, 11.0 / 27, 20.0 / 27, 5.0 / 27, 14.0 / 27, 23.0 / 27, 8.0 / 27, 17.0 / 27, 26.0 / 27 }; dimensionality = 2; points = (int)Math.Pow(3.0, 3) - 1; // three cycles of the higher dimension for (i = 0; i < points; i++) { point = HaltonSequence.Halton(i, dimensionality); double error = Math.Abs(point[0] - vanderCorputSequenceModuloTwo[i]); if (error > tolerance) { Debug.Print("First component of " + i + 1 + " draw (" + +point[0] + ") in 2-D Halton sequence is not in the " + "van der Corput sequence modulo two: " + "it should have been " + vanderCorputSequenceModuloTwo[i] + " (error = " + error + ")"); } error = Math.Abs(point[1] - vanderCorputSequenceModuloThree[i]); if (error > tolerance) { Debug.Print("Second component of " + i + 1 + " draw (" + +point[1] + ") in 2-D Halton sequence is not in the " + "van der Corput sequence modulo three: " + "it should have been " + vanderCorputSequenceModuloThree[i] + " (error = " + error + ")"); } } }
public void GetElement_InvalidIndex_Throws() { Assert.That(() => HaltonSequence.GetElement(-1, 1), Throws.ArgumentException); }
public void GetElement_InvalidDimensions_Throws() { Assert.That(() => HaltonSequence.GetElement(0, 0), Throws.ArgumentException); }