public void OnChunkGeneratedEmpty(int hm) { var vp = Vector3Int.zero; var neighbourhood = neighbourhoodFor(ref vp); heightMapYValue = hm; RunLightingGeneration(neighbourhood.center.ChunkID); var expectedLv = new LightValue() { Sun = (hm < 0) ? maxIntensity : 0, Dynamic = 0 }; for (int z = 0; z < chunkDimensions.z; z++) { for (int y = 0; y < chunkDimensions.y; y++) { for (int x = 0; x < chunkDimensions.x; x++) { Assert.AreEqual(expectedLv, neighbourhood.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z}"); } } } }
public void OnChunkGeneratedUnderground() { var chunkId = Vector3Int.down; var expectedLv = new LightValue() { Sun = 0, Dynamic = 0 }; //Generate chunk var neighbourhood = new ChunkNeighbourhood(chunkId, GetMockChunkData); //Ground level is at 0, so the chunk will think it has no sunlight heightMapYValue = 0; RunLightingGeneration(neighbourhood.center.ChunkID); //PrintSlice(neighbourhood, 0,false); var chunkData = GetMockChunkData(chunkId); for (int z = 0; z < chunkDimensions.z; z++) { for (int y = 0; y < chunkDimensions.y; y++) { for (int x = 0; x < chunkDimensions.x; x++) { Assert.AreEqual(expectedLv, chunkData.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z}"); } } } }
/// <summary> /// Returns the coefficient to be used in order to display the results according to the preferences of the IResult /// object used to create the instance of this object. Returns the prefered functional unit divided by the functional unit. /// /// In case of the FunctionalUnit is null or the PreferedUnit is null, this method returns a ratio of 1. This is usefull to /// display the Inputs results and the TransportationSteps results which are accounted for all outputs and not a specific one. /// In these cases instead of defining a PreferedUnit for each output we prefer to define none to make things simpler (see InputResult.GetResults) /// /// Before display all results must be multiplied by this coefficient /// /// May return a NullReferenceExeption if the IResult object does not define FunctinoalUnit, PreferedDisplayedUnit or PreferedDisplayedAmount /// </summary> /// <param name="results"></param> /// <returns></returns> internal static double GetFunctionalRatio(GData data, Results results, int producedResourceId) { if (results != null && results.CustomFunctionalUnitPreference != null && results.CustomFunctionalUnitPreference.PreferredUnitExpression != null) { LightValue functionalUnit = new LightValue(1.0, results.BottomDim); LightValue preferedFunctionalUnit = GetPreferedVisualizationFunctionalUnit(data, results, producedResourceId); switch (preferedFunctionalUnit.Dim) { case DimensionUtils.MASS: // HARDCODED { functionalUnit = data.ResourcesData[producedResourceId].ConvertToMass(functionalUnit); } break; case DimensionUtils.ENERGY: // HARDCODED { functionalUnit = data.ResourcesData[producedResourceId].ConvertToEnergy(functionalUnit); } break; case DimensionUtils.VOLUME: // HARDCODED { functionalUnit = data.ResourcesData[producedResourceId].ConvertToVolume(functionalUnit); } break; } return preferedFunctionalUnit.Value / functionalUnit.Value; } else return 1; }
/// <summary> /// Returns the coefficient to be used in order to display the results according to the preferences of the IResult /// object used to create the instance of this object. Returns the prefered functional unit divided by the functional unit. /// /// In case of the FunctionalUnit is null or the PreferedUnit is null, this method returns a ratio of 1. This is usefull to /// display the Inputs results and the TransportationSteps results which are accounted for all outputs and not a specific one. /// In these cases instead of defining a PreferedUnit for each output we prefer to define none to make things simpler (see InputResult.GetResults) /// /// Before display all results must be multiplied by this coefficient /// /// May return a NullReferenceExeption if the IResult object does not define FunctinoalUnit, PreferedDisplayedUnit or PreferedDisplayedAmount /// </summary> /// <param name="results"></param> /// <returns></returns> internal static double GetFunctionalRatio(GData data, Results results, int producedResourceId) { if (results != null && results.CustomFunctionalUnitPreference != null && results.CustomFunctionalUnitPreference.PreferredUnitExpression != null) { LightValue functionalUnit = new LightValue(1.0, results.BottomDim); LightValue preferedFunctionalUnit = GetPreferedVisualizationFunctionalUnit(data, results, producedResourceId); switch (preferedFunctionalUnit.Dim) { case DimensionUtils.MASS: // HARDCODED { functionalUnit = data.ResourcesData[producedResourceId].ConvertToMass(functionalUnit); } break; case DimensionUtils.ENERGY: // HARDCODED { functionalUnit = data.ResourcesData[producedResourceId].ConvertToEnergy(functionalUnit); } break; case DimensionUtils.VOLUME: // HARDCODED { functionalUnit = data.ResourcesData[producedResourceId].ConvertToVolume(functionalUnit); } break; } return(preferedFunctionalUnit.Value / functionalUnit.Value); } else { return(1); } }
public void Dynamic() { LightValue lv = new LightValue(); for (int i = 0; i < LightValue.IntensityRange; i++) { lv.Dynamic = i; Assert.AreEqual(i, lv.Dynamic, $"Light incorrect for value {i}"); } }
public void Sunlight() { LightValue lv = new LightValue(); for (int i = 0; i < LightValue.IntensityRange; i++) { lv.Sun = i; Assert.AreEqual(i, lv.Sun, $"Light incorrect for value {i}"); } }
public void OnChunkGeneratedWithLightWithNeighbourFullyGenerated(int hm) { var vp = Vector3Int.zero; var lampPos = vp; var neighbourhood = neighbourhoodFor(ref vp); //act as if this voxel was generated as part of the chunk neighbourhood.SetVoxel(vp.x, vp.y, vp.z, lampId); heightMapYValue = hm; //generate another chunk next to this one, the light should spill in from the zero chunk var tstChunkId = new Vector3Int(-1, 0, 0); RunLightingGeneration(tstChunkId); lightManager.Update(); //run the generation action for the zero chunk RunLightingGeneration(neighbourhood.center.ChunkID); lightManager.Update(); //PrintSlice(neighbourhood, 0); ///Should have propagated the lamp light only within the center chunk ///and the newly added chunk for (int z = -maxIntensity; z <= maxIntensity; z++) { for (int y = -maxIntensity; y <= maxIntensity; y++) { for (int x = -maxIntensity; x <= maxIntensity; x++) { var pos = new Vector3Int(x, y, z); var expectedLv = new LightValue() { Sun = (hm < 0) ? maxIntensity : 0 }; expectedLv.Dynamic = math.max(maxIntensity - pos.ManhattanMagnitude(), 0); if (!insideChunkId(pos, Vector3Int.zero) && !insideChunkId(pos, tstChunkId)) { expectedLv.Dynamic = 0; expectedLv.Sun = 0; } if (pos.Equals(lampPos)) {//This is where the lamp is, lamps are opaque to sunlight expectedLv.Sun = 0; } Assert.AreEqual(expectedLv, neighbourhood.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z}"); } } } }
public void MultiplePropagationsIntoSameChunkInOneUpdate() { lightManager.Parallel = true;//Parallel execution //Ground level is at 0, so the lower chunk will at first think it has no sunlight heightMapYValue = 0; Vector3Int testChunkId = Vector3Int.down; var upId = testChunkId + Vector3Int.up; var adjacentId = testChunkId + Vector3Int.left; var neighbourhood = new ChunkNeighbourhood(testChunkId, GetMockChunkData); //The lamp in the adjacent chunk should cause a propagation update in the test chunk var lampPos = new Vector3Int(-1, 0, 0); neighbourhood.SetVoxel(lampPos.x, lampPos.y, lampPos.z, lampId); //generate test chunk RunLightingGeneration(testChunkId); lightManager.Update(); //generate up chunk, then adjacent chunk. RunLightingGeneration(upId); RunLightingGeneration(adjacentId); lightManager.Update();//Run propagations in the same update ///This order could result in no sunlight in the test chunk if race conditions are present, ///we are testing that there isn't a race condition. var expectedSunlight = LightValue.MaxIntensity; var testChunkData = GetMockChunkData(testChunkId); for (int z = 0; z < chunkDimensions.z; z++) { for (int y = 0; y < chunkDimensions.y; y++) { for (int x = 0; x < chunkDimensions.x; x++) { var pos = new Vector3Int(x, y, z); var expectedDynamic = math.max(maxIntensity - (pos - lampPos).ManhattanMagnitude(), 0); var expectedLv = new LightValue() { Dynamic = expectedDynamic, Sun = expectedSunlight }; Assert.AreEqual(expectedLv, testChunkData.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z}"); } } } }
public void OnChunksGeneratedSunlightTriple(int[] order) { Vector3Int[] ids = new Vector3Int[] { Vector3Int.zero, Vector3Int.down, Vector3Int.down * 2 }; IChunkData[] chunkDatas = new IChunkData[] { GetMockChunkData(ids[0]), GetMockChunkData(ids[1]), GetMockChunkData(ids[2]), }; //Ground level is at 0, so the lower chunk will at first think it has no sunlight heightMapYValue = 0; foreach (var index in order) { RunLightingGeneration(ids[index]); lightManager.Update(); } //var bottomNeigh = new ChunkNeighbourhood(lowChunkData, GetMockChunkData); //Debug.Log("TopSlice"); //PrintSlice(bottomNeigh, 15,false); //Debug.Log("BottomSlice"); //PrintSlice(bottomNeigh, 0, false); var expectedLv = new LightValue() { Sun = maxIntensity, Dynamic = 0 }; for (int z = 0; z < chunkDimensions.z; z++) { for (int y = 0; y < chunkDimensions.y; y++) { for (int x = 0; x < chunkDimensions.x; x++) { for (int i = 0; i < ids.Length; i++) { Assert.AreEqual(expectedLv, chunkDatas[i].GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z} in chunk {i}"); } } } } }
internal static string NiceValueWithAttribute(LightValue value, string preferedExpression = "") { double automaticScalingSlope = 1; string overrideUnitAttribute = ""; return(GuiUtils.FormatSIValue(value.Value , 2 //DEFINES THE FORMATTING FOR VALUES , out overrideUnitAttribute , out automaticScalingSlope , false , 16 //DEFINES HOW MANY DIGITS YOU WANT TO SEE , value.Dim , preferedExpression)); // +" " + overrideUnitAttribute; }
public void Mixed() { LightValue lv = new LightValue(); for (int i = 0; i < LightValue.IntensityRange; i++) { for (int j = 0; j < LightValue.IntensityRange; j++) { lv.Sun = i; Assert.AreEqual(i, lv.Sun, $"Sun light incorrect for value {i},{j}"); lv.Dynamic = j; Assert.AreEqual(j, lv.Dynamic, $"Dynamic light incorrect for value {i},{j}"); } } }
/// <summary> /// Returns the functional unit to be used on display: User prefered, default million btu or functional unit of the /// process in case of the database does not contains enough information to convert to one million btu /// </summary> /// <param name="data"></param> /// <param name="results"></param> /// <param name="producedResourceId"></param> /// <returns></returns> internal static LightValue GetPreferedVisualizationFunctionalUnit(GData data, Results results, int producedResourceId) { LightValue preferedFunctionalUnit; if (results.CustomFunctionalUnitPreference.enabled) { preferedFunctionalUnit = new LightValue(results.CustomFunctionalUnitPreference.Amount, results.CustomFunctionalUnitPreference.PreferredUnitExpression); } else if (data.ResourcesData[producedResourceId].CanConvertTo(DimensionUtils.ENERGY, new LightValue(1.0, results.BottomDim))) { preferedFunctionalUnit = new LightValue(1, "MJ"); } else { preferedFunctionalUnit = new LightValue(1.0, results.BottomDim); } return(preferedFunctionalUnit); }
public void OnChunksGeneratedSunlight(bool topToBottom) { int first = 0; int second = 1; if (!topToBottom) { Utils.Helpers.Swap(ref first, ref second); } Vector3Int[] ids = new Vector3Int[] { Vector3Int.zero, Vector3Int.down }; var upChunkData = GetMockChunkData(ids[0]); var lowChunkData = GetMockChunkData(ids[1]); var expectedLv = new LightValue() { Sun = 0, Dynamic = 0 }; //Ground level is at 0, so the lower chunk will at first think it has no sunlight heightMapYValue = 0; //Generate first chunk RunLightingGeneration(ids[first]); lightManager.Update(); //Second chunk should not have sunlight yet var secondChunkData = GetMockChunkData(ids[second]); for (int z = 0; z < chunkDimensions.z; z++) { for (int y = 0; y < chunkDimensions.y; y++) { for (int x = 0; x < chunkDimensions.x; x++) { Assert.AreEqual(expectedLv, secondChunkData.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z} in second chunk"); } } } //Generate second chunk RunLightingGeneration(ids[second]); lightManager.Update(); var bottomNeigh = new ChunkNeighbourhood(lowChunkData, GetMockChunkData); //Debug.Log("TopSlice"); //PrintSlice(bottomNeigh, 15,false); //Debug.Log("BottomSlice"); //PrintSlice(bottomNeigh, 0, false); expectedLv = new LightValue() { Sun = maxIntensity, Dynamic = 0 }; for (int z = 0; z < chunkDimensions.z; z++) { for (int y = 0; y < chunkDimensions.y; y++) { for (int x = 0; x < chunkDimensions.x; x++) { Assert.AreEqual(expectedLv, upChunkData.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z} in upper chunk"); Assert.AreEqual(expectedLv, lowChunkData.GetLight(x, y, z), $"Light value not as expected for position {x},{y},{z} in lower chunk"); } } } }
internal static string NiceValueWithAttribute(LightValue value, string preferedExpression = "") { double automaticScalingSlope = 1; string overrideUnitAttribute = ""; return GuiUtils.FormatSIValue(value.Value , 2 //DEFINES THE FORMATTING FOR VALUES , out overrideUnitAttribute , out automaticScalingSlope , false , 16 //DEFINES HOW MANY DIGITS YOU WANT TO SEE , value.Dim , preferedExpression);// +" " + overrideUnitAttribute; }
public override bool GetSFRValue(Bitmap bmp, ref SFRValue SFRValue, ref RectInfo rectInfo, Rectangle[] rectangles, ref LightValue lightValue, bool TestLight = false) { SFRInfo info = new SFRInfo(); // Rectangle[] rectangles = new Rectangle[13]; SFR_C_Info sFR_C_Info = new SFR_C_Info(); SFR_C_Info YData = new SFR_C_Info(); double frequency = ParamSetMgr.GetInstance().GetDoubleParam("[SFR] dSFR_Parameter"); bool bRet = false; try { if (bmp == null) { return(false); } Bitmap temp = (Bitmap)bmp.Clone(); int nWidth = temp.Width; int nHeight = temp.Height; byte[] byBuffer = ImageChangeHelper.Instance.Rgb2Gray(bmp); unsafe { fixed(byte *byBufferptr = byBuffer) { bRet = ActiveAlignment.CalibrationMode_Collimators(byBufferptr, nWidth, nHeight, ref sFR_C_Info, ref YData); } } temp.Dispose(); //sfr 转换 SFRValue = AlgChangeHelper.Collimator_Info2Value(sFR_C_Info); rectInfo = AlgChangeHelper.Collimator_Info2Rect(sFR_C_Info); } catch { } double[] value = new double[5]; try { value[0] = YData.block[0].dValue; value[1] = YData.block[1].dValue; value[2] = YData.block[2].dValue; value[3] = YData.block[3].dValue; value[4] = YData.block[4].dValue; } catch (Exception ex) { value[0] = -1; value[1] = -1; value[2] = -1; value[3] = -1; value[4] = -1; //return false; } lightValue.blockValue = value; return(bRet); }
public bool GetSFRValue(Bitmap bmp, ref SFRValue SFRValue, ref RectInfo rectInfo, Rectangle[] rectangles, ref LightValue lightValue, bool TestLight = false) { if (!bLoad) { return(false); } AlgorithmBase tempModuleBase = GetAlgByIndexID(); if (tempModuleBase != null) { bool result = tempModuleBase.GetSFRValue(bmp, ref SFRValue, ref rectInfo, rectangles, ref lightValue, TestLight); if (SFRValue != null) { for (int i = 0; i < SFRValue.block.Length; i++) { if (SFRValue.block[i].dValue > ParamSetMgr.GetInstance().GetDoubleParam("SFR最大值")) { SFRValue.block[i].dValue = -1; } } } return(result); } else { return(false); } }
private FaceDescriptor makeFaceDescriptor(VoxelTypeID typeId, Direction originalDirection, LightValue lightValue, VoxelRotation rotation = default) { if (typeId == VoxelTypeID.AIR_ID) { return(nullFace); } var faceDirection = originalDirection; if (!rotation.isBlank) { ///Face direction needs to be the direction index of the face currently pointing in the original ///direction. Therefore it is the direction such that applying the rotation gives the original direction. faceDirection = directionRotator.GetDirectionBeforeRotation(originalDirection, rotation); } FaceDescriptor faceDescriptor = new FaceDescriptor() { typeId = typeId, faceDirection = faceDirection, rotation = rotation, lightValue = lightValue }; return(faceDescriptor); }
/// <summary> /// Returns the functional unit to be used on display: User prefered, default million btu or functional unit of the /// process in case of the database does not contains enough information to convert to one million btu /// </summary> /// <param name="data"></param> /// <param name="results"></param> /// <param name="producedResourceId"></param> /// <returns></returns> internal static LightValue GetPreferedVisualizationFunctionalUnit(GData data, Results results, int producedResourceId) { LightValue preferedFunctionalUnit; if (results.CustomFunctionalUnitPreference.enabled) preferedFunctionalUnit = new LightValue(results.CustomFunctionalUnitPreference.Amount, results.CustomFunctionalUnitPreference.PreferredUnitExpression); else if (data.ResourcesData[producedResourceId].CanConvertTo(DimensionUtils.ENERGY, new LightValue(1.0, results.BottomDim))) preferedFunctionalUnit = new LightValue(1, "MJ"); else preferedFunctionalUnit = new LightValue(1.0, results.BottomDim); return preferedFunctionalUnit; }
public override bool GetSFRValue(Bitmap bmp, ref SFRValue SFRValue, ref RectInfo rectInfo, Rectangle[] rectangles, ref LightValue lightValue, bool TestLight = false) { SFRInfo info = new SFRInfo(); ObjectInfo objectInfo = new ObjectInfo(); // Rectangle[] rectangles = new Rectangle[13]; if (bmp == null) { return(false); } Bitmap temp = (Bitmap)bmp.Clone(); bool bRet = false; int nWidth = temp.Width; int nHeight = temp.Height; byte[] byBuffer = ImageChangeHelper.Instance.Rgb2Gray(bmp); unsafe { fixed(byte *byBufferptr = byBuffer) { bRet = ActiveAlignment.GetSFRValue_Sector(byBufferptr, nWidth, nHeight, ref info, ref objectInfo, rectangles); } } temp.Dispose(); //sfr 转换 if (TestLight) { double[] value = new double[5]; HObject ho_Image = null, ho_GrayImage = null; try { HObject ho_SelectedRegions0 = null; HObject ho_SelectedRegions1 = null; HObject ho_SelectedRegions2 = null; HObject ho_SelectedRegions3 = null; HObject ho_SelectedRegions4 = null; HTuple hv_XField = null, hv_YField = null; HTuple hv_CenterROIR = null, hv_CenterROIC = null, hv_CenterMinArea = null, hv_CenterSFRThreshold = null, hv_CenterClosing = null; HTuple hv_Corner1ROIR = null, hv_Corner1ROIC = null, hv_Corner1MinArea = null, hv_Corner1SFRThreshold = null, hv_Corner1Closing = null; HTuple CenterMean = null, CenterDeviation = null; HTuple Corner1Mean = null, Corner1Deviation = null; HTuple Corner2Mean = null, Corner2Deviation = null; HTuple Corner3Mean = null, Corner3Deviation = null; HTuple Corner4Mean = null, Corner4Deviation = null; hv_CenterROIR = ParamSetMgr.GetInstance().GetIntParam("[SFR] nCenterROIW"); hv_CenterROIC = ParamSetMgr.GetInstance().GetIntParam("[SFR] nCenterROIH"); hv_CenterMinArea = ParamSetMgr.GetInstance().GetDoubleParam("MF中心对心最小面积"); hv_CenterSFRThreshold = ParamSetMgr.GetInstance().GetDoubleParam("MF中心对心阈值设置"); hv_CenterClosing = ParamSetMgr.GetInstance().GetDoubleParam("MF中心对心膨胀系数"); hv_XField = ParamSetMgr.GetInstance().GetDoubleParam("[SFR] dCorner1XField"); hv_YField = ParamSetMgr.GetInstance().GetDoubleParam("[SFR] dCorner1YField"); hv_Corner1ROIR = ParamSetMgr.GetInstance().GetIntParam("[SFR] nCorner1ROIW"); hv_Corner1ROIC = ParamSetMgr.GetInstance().GetIntParam("[SFR] nCorner1ROIH"); hv_Corner1MinArea = ParamSetMgr.GetInstance().GetDoubleParam("MF_Corner1最小面积"); hv_Corner1SFRThreshold = ParamSetMgr.GetInstance().GetDoubleParam("MF_Corner1阈值设置"); hv_Corner1Closing = ParamSetMgr.GetInstance().GetDoubleParam("MF_Corner1膨胀系数"); ImageChangeHelper.Instance.Bitmap2HObject((Bitmap)bmp.Clone(), ref ho_Image); FindCenterRegions(ho_Image, hv_CenterROIR, hv_CenterROIC, 0, 0, hv_CenterMinArea, hv_CenterSFRThreshold, hv_CenterClosing, ref ho_SelectedRegions0); FindCenterRegions(ho_Image, hv_Corner1ROIR, hv_Corner1ROIC, -hv_XField, -hv_YField, hv_Corner1MinArea, hv_Corner1SFRThreshold, hv_Corner1Closing, ref ho_SelectedRegions1); FindCenterRegions(ho_Image, hv_Corner1ROIR, hv_Corner1ROIC, hv_XField, -hv_YField, hv_Corner1MinArea, hv_Corner1SFRThreshold, hv_Corner1Closing, ref ho_SelectedRegions2); FindCenterRegions(ho_Image, hv_Corner1ROIR, hv_Corner1ROIC, -hv_XField, hv_YField, hv_Corner1MinArea, hv_Corner1SFRThreshold, hv_Corner1Closing, ref ho_SelectedRegions3); FindCenterRegions(ho_Image, hv_Corner1ROIR, hv_Corner1ROIC, hv_XField, hv_YField, hv_Corner1MinArea, hv_Corner1SFRThreshold, hv_Corner1Closing, ref ho_SelectedRegions4); HOperatorSet.Intensity(ho_SelectedRegions0, ho_Image, out CenterMean, out CenterDeviation); HOperatorSet.Intensity(ho_SelectedRegions1, ho_Image, out Corner1Mean, out Corner1Deviation); HOperatorSet.Intensity(ho_SelectedRegions2, ho_Image, out Corner2Mean, out Corner2Deviation); HOperatorSet.Intensity(ho_SelectedRegions3, ho_Image, out Corner3Mean, out Corner3Deviation); HOperatorSet.Intensity(ho_SelectedRegions4, ho_Image, out Corner4Mean, out Corner4Deviation); value[0] = CenterMean.D; value[1] = Corner1Mean.D; value[2] = Corner2Mean.D; value[3] = Corner3Mean.D; value[4] = Corner4Mean.D; } catch (Exception ex) { value[0] = -1; value[1] = -1; value[2] = -1; value[3] = -1; value[4] = -1; //return false; } lightValue.blockValue = value; } SFRValue = AlgChangeHelper.Sector_Info2Value(info); rectInfo = AlgChangeHelper.Sector_Info2Value(objectInfo); return(bRet); }
/// <summary> /// Program entry point /// </summary> /// <param name="args"></param> static void Main(string[] args) { #region preproceiing parsing the user inputs Console.WriteLine("Parsing given parameters..."); //Using the filename provided as the first argument string fileName = args[0]; //Using the years defined in the second argument string years = args[1]; string[] yearsSplit = years.Split(','); List<int> yearsList = new List<int>(); int temp; foreach (string y in yearsSplit) if (int.TryParse(y, out temp)) yearsList.Add(temp); //Using the pathways and mix id provided in the third argument string pm = args[2]; string[] pms = pm.Split(','); List<InputResourceReference> inRef = new List<InputResourceReference>(); foreach (string s in pms) { if (s[0] == 'p') {//this is a pathway reference if (int.TryParse(s.Substring(1, s.Length - 1), out temp)) { InputResourceReference pRef = new InputResourceReference(-1, temp, Enumerators.SourceType.Pathway); inRef.Add(pRef); } } else if (s[0] == 'm') {//this is a mix reference if (int.TryParse(s.Substring(1, s.Length - 1), out temp)) { InputResourceReference mRef = new InputResourceReference(-1, temp, Enumerators.SourceType.Mix); inRef.Add(mRef); } } } #endregion #region loading units file and data file Console.WriteLine("Building units context..."); //Build units context before loading the database Units.BuildContext(); Console.WriteLine("Loading datafile..."); //Loading the database GProject project = new GProject(); project.Load(fileName); #endregion #region preprocessing the pathways/mixes we want to record by finding their main output resource //Assign main output resource IDs to all the inputsResourceReferences foreach (InputResourceReference iref in inRef) { if (iref.SourceType == Greet.DataStructureV4.Interfaces.Enumerators.SourceType.Pathway) { if (project.Dataset.PathwaysData.ContainsKey(iref.SourceMixOrPathwayID)) iref.ResourceId = project.Dataset.PathwaysData[iref.SourceMixOrPathwayID].MainOutputResourceID; } else if (iref.SourceType == Greet.DataStructureV4.Interfaces.Enumerators.SourceType.Mix) { if (project.Dataset.MixesData.ContainsKey(iref.SourceMixOrPathwayID)) iref.ResourceId = project.Dataset.MixesData[iref.SourceMixOrPathwayID].MainOutputResourceID; } } #endregion #region running the calculations for each year and storing the results //Creating a new instance of a dictionary used to store results of the simulations Dictionary<InputResourceReference, Dictionary<int, Results>> savedResults = new Dictionary<InputResourceReference, Dictionary<int, Results>>(); //Running simulations for every provided years foreach (int simulationYear in yearsList) { Console.WriteLine("Running calculations for year " + simulationYear); //Set the current year for simulations BasicParameters.SelectedYear = project.Dataset.ParametersData.CreateUnregisteredParameter(project.Dataset, "", simulationYear); Calculator calc = new Calculator(); //Run the simulations for the loaded project and defined year, we need to wait completion as the RunCalculationMethod is Async var manualEvent = new ManualResetEvent(false); calc.CalculationDoneEvent += () => manualEvent.Set(); calc.RunCalculations(project); manualEvent.WaitOne(); //Loop over all the pathways and mixes ID that we wish to save foreach (InputResourceReference pathMixToSave in inRef) { if (!savedResults.ContainsKey(pathMixToSave)) savedResults.Add(pathMixToSave, new Dictionary<int, Results>()); if(!savedResults[pathMixToSave].ContainsKey(simulationYear)) { //Pull the results and add them to the dictionary used to store results Results results; if(pathMixToSave.SourceType == Enumerators.SourceType.Pathway) results = Convenience.Clone(project.Dataset.PathwaysData[pathMixToSave.SourceMixOrPathwayID].getMainOutputResults().Results); else results = Convenience.Clone(project.Dataset.MixesData[pathMixToSave.SourceMixOrPathwayID].getMainOutputResults().Results); savedResults[pathMixToSave].Add(simulationYear, results); } } } #endregion #region exporting all the results in a text file per pathway and per mix //Export all the desired results to an Excel spreadsheet Console.WriteLine("Export all selected results..."); string preferedMass = "g"; string preferedEnergy = "Btu"; string preferedVolume = "gal"; foreach (KeyValuePair<InputResourceReference, Dictionary<int, Results>> pair in savedResults) { DataTable dt = new DataTable(); List<string> resGroups = new List<string>() { "Total Energy", "Fossil Fuel", "Coal Fuel", "Natural Gas Fuel", "Petroleum Fuel", "Water" }; List<string> pollutants = new List<string>() { "VOC", "CO", "NOx", "PM10", "PM2.5", "SOx", "BC", "POC", "CH4", "N2O", "CO2", "CO2_Biogenic" }; List<string> polGroups = new List<string>() { "GHG-100" }; List<string> urbanPoll = new List<string>() { "VOC", "CO", "NOx", "PM10", "PM2.5", "SOx", "BC", "POC", "CH4", "N2O" }; Results resultsFU = pair.Value.Values.FirstOrDefault(); string functionalUnit = "Per "; if (resultsFU != null) functionalUnit += GetPreferedVisualizationFunctionalUnitString(project.Dataset, resultsFU, pair.Key.ResourceId); dt.Columns.Add("Items " + functionalUnit); foreach (int simulationYear in pair.Value.Keys) dt.Columns.Add(simulationYear.ToString()); List<string> rowString = new List<string>(); #region total energy and energy groups foreach (string resGrp in resGroups) { rowString = new List<string>(); if (resGrp=="Water") rowString.Add(resGrp+" ("+preferedVolume+")"); else rowString.Add(resGrp + " (" + preferedEnergy + ")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); if (resGrp == "Total Energy") { LightValue totalE = results.wellToProductEnem.materialsAmounts.TotalEnergy(); rowString.Add(NiceValueWithAttribute(totalE * amountRatio, preferedEnergy)); } else { Dictionary<int, IValue> resGroupes = results.WellToProductResourcesGroups(project.Dataset); Group resGrpSelected = project.Dataset.ResourcesData.Groups.Values.SingleOrDefault(item => item.Name == resGrp); if (resGrpSelected != null) { int resGrpId = resGrpSelected.Id; LightValue groupValue = new LightValue(resGroupes[resGrpId].Value, resGroupes[resGrpId].UnitExpression); if (groupValue.Dim == DimensionUtils.ENERGY) rowString.Add(NiceValueWithAttribute(groupValue * amountRatio, preferedEnergy)); else rowString.Add(NiceValueWithAttribute(groupValue * amountRatio, preferedVolume)); } else rowString.Add("0"); } } dt.Rows.Add(rowString.ToArray()); } #endregion #region wtp emissions foreach (string poll in pollutants) { rowString = new List<string>(); rowString.Add(poll+" ("+preferedMass+")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); int polId = project.Dataset.GasesData.Values.Single(item => item.Name == poll).Id; rowString.Add(NiceValueWithAttribute( new LightValue(results.wellToProductEnem.emissions[polId], DimensionUtils.MASS) * amountRatio , preferedMass)); } dt.Rows.Add(rowString.ToArray()); } #endregion #region wtp Groups (here only GHG 100) foreach (string resGrp in polGroups) { rowString = new List<string>(); rowString.Add(resGrp+ " ("+ preferedMass+")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); Dictionary<int, IValue> emGroupes = pair.Value[simulationYear].WellToProductEmissionsGroups(project.Dataset); Group resGrpSelected = project.Dataset.GasesData.Groups.Values.SingleOrDefault(item => item.Name == resGrp); if (resGrpSelected != null) { int grpId = resGrpSelected.Id; rowString.Add(NiceValueWithAttribute(new LightValue(emGroupes[grpId].Value, emGroupes[grpId].UnitExpression) * amountRatio, preferedMass)); } else rowString.Add("0"); } dt.Rows.Add(rowString.ToArray()); } #endregion #region urban emissions foreach (string poll in pollutants) { rowString = new List<string>(); rowString.Add("Urban " +poll+" ("+preferedMass+")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); int polId = project.Dataset.GasesData.Values.Single(item => item.Name == poll).Id; rowString.Add(NiceValueWithAttribute(new LightValue(results.wellToProductUrbanEmission[polId], DimensionUtils.MASS) * amountRatio, preferedMass)); } dt.Rows.Add(rowString.ToArray()); } #endregion string value = ConvertDataTableToString(dt); System.IO.File.WriteAllText("Results-" + pair.Key.SourceType.ToString() + "-" + pair.Key.SourceMixOrPathwayID.ToString() + ".txt", value); } #endregion }
public void SetLight(Vector3Int pos, LightValue lightValue) { lightChunk[pos.x, pos.y, pos.z] = lightValue; }
public void SetLight(int x, int y, int z, LightValue value) { var chunkData = extendedIndex(ref x, ref y, ref z); chunkData.SetLight(x, y, z, value); }
/// <summary> /// Program entry point /// </summary> /// <param name="args"></param> static void Main(string[] args) { #region preproceiing parsing the user inputs Console.WriteLine("Parsing given parameters..."); //Using the filename provided as the first argument string fileName = args[0]; //Using the years defined in the second argument string years = args[1]; string[] yearsSplit = years.Split(','); List <int> yearsList = new List <int>(); int temp; foreach (string y in yearsSplit) { if (int.TryParse(y, out temp)) { yearsList.Add(temp); } } //Using the pathways and mix id provided in the third argument string pm = args[2]; string[] pms = pm.Split(','); List <InputResourceReference> inRef = new List <InputResourceReference>(); foreach (string s in pms) { if (s[0] == 'p') {//this is a pathway reference if (int.TryParse(s.Substring(1, s.Length - 1), out temp)) { InputResourceReference pRef = new InputResourceReference(-1, temp, Enumerators.SourceType.Pathway); inRef.Add(pRef); } } else if (s[0] == 'm') {//this is a mix reference if (int.TryParse(s.Substring(1, s.Length - 1), out temp)) { InputResourceReference mRef = new InputResourceReference(-1, temp, Enumerators.SourceType.Mix); inRef.Add(mRef); } } } #endregion #region loading units file and data file Console.WriteLine("Building units context..."); //Build units context before loading the database Units.BuildContext(); Console.WriteLine("Loading datafile..."); //Loading the database GProject project = new GProject(); project.Load(fileName); #endregion #region preprocessing the pathways/mixes we want to record by finding their main output resource //Assign main output resource IDs to all the inputsResourceReferences foreach (InputResourceReference iref in inRef) { if (iref.SourceType == Greet.DataStructureV4.Interfaces.Enumerators.SourceType.Pathway) { if (project.Dataset.PathwaysData.ContainsKey(iref.SourceMixOrPathwayID)) { iref.ResourceId = project.Dataset.PathwaysData[iref.SourceMixOrPathwayID].MainOutputResourceID; } } else if (iref.SourceType == Greet.DataStructureV4.Interfaces.Enumerators.SourceType.Mix) { if (project.Dataset.MixesData.ContainsKey(iref.SourceMixOrPathwayID)) { iref.ResourceId = project.Dataset.MixesData[iref.SourceMixOrPathwayID].MainOutputResourceID; } } } #endregion #region running the calculations for each year and storing the results //Creating a new instance of a dictionary used to store results of the simulations Dictionary <InputResourceReference, Dictionary <int, Results> > savedResults = new Dictionary <InputResourceReference, Dictionary <int, Results> >(); //Running simulations for every provided years foreach (int simulationYear in yearsList) { Console.WriteLine("Running calculations for year " + simulationYear); //Set the current year for simulations BasicParameters.SelectedYear = project.Dataset.ParametersData.CreateUnregisteredParameter(project.Dataset, "", simulationYear); Calculator calc = new Calculator(); //Run the simulations for the loaded project and defined year, we need to wait completion as the RunCalculationMethod is Async var manualEvent = new ManualResetEvent(false); calc.CalculationDoneEvent += () => manualEvent.Set(); calc.RunCalculations(project); manualEvent.WaitOne(); //Loop over all the pathways and mixes ID that we wish to save foreach (InputResourceReference pathMixToSave in inRef) { if (!savedResults.ContainsKey(pathMixToSave)) { savedResults.Add(pathMixToSave, new Dictionary <int, Results>()); } if (!savedResults[pathMixToSave].ContainsKey(simulationYear)) { //Pull the results and add them to the dictionary used to store results Results results; if (pathMixToSave.SourceType == Enumerators.SourceType.Pathway) { results = Convenience.Clone(project.Dataset.PathwaysData[pathMixToSave.SourceMixOrPathwayID].getMainOutputResults().Results); } else { results = Convenience.Clone(project.Dataset.MixesData[pathMixToSave.SourceMixOrPathwayID].getMainOutputResults().Results); } savedResults[pathMixToSave].Add(simulationYear, results); } } } #endregion #region exporting all the results in a text file per pathway and per mix //Export all the desired results to an Excel spreadsheet Console.WriteLine("Export all selected results..."); string preferedMass = "g"; string preferedEnergy = "Btu"; string preferedVolume = "gal"; foreach (KeyValuePair <InputResourceReference, Dictionary <int, Results> > pair in savedResults) { DataTable dt = new DataTable(); List <string> resGroups = new List <string>() { "Total Energy", "Fossil Fuel", "Coal Fuel", "Natural Gas Fuel", "Petroleum Fuel", "Water" }; List <string> pollutants = new List <string>() { "VOC", "CO", "NOx", "PM10", "PM2.5", "SOx", "BC", "POC", "CH4", "N2O", "CO2", "CO2_Biogenic" }; List <string> polGroups = new List <string>() { "GHG-100" }; List <string> urbanPoll = new List <string>() { "VOC", "CO", "NOx", "PM10", "PM2.5", "SOx", "BC", "POC", "CH4", "N2O" }; Results resultsFU = pair.Value.Values.FirstOrDefault(); string functionalUnit = "Per "; if (resultsFU != null) { functionalUnit += GetPreferedVisualizationFunctionalUnitString(project.Dataset, resultsFU, pair.Key.ResourceId); } dt.Columns.Add("Items " + functionalUnit); foreach (int simulationYear in pair.Value.Keys) { dt.Columns.Add(simulationYear.ToString()); } List <string> rowString = new List <string>(); #region total energy and energy groups foreach (string resGrp in resGroups) { rowString = new List <string>(); if (resGrp == "Water") { rowString.Add(resGrp + " (" + preferedVolume + ")"); } else { rowString.Add(resGrp + " (" + preferedEnergy + ")"); } foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); if (resGrp == "Total Energy") { LightValue totalE = results.wellToProductEnem.materialsAmounts.TotalEnergy(); rowString.Add(NiceValueWithAttribute(totalE * amountRatio, preferedEnergy)); } else { Dictionary <int, IValue> resGroupes = results.WellToProductResourcesGroups(project.Dataset); Group resGrpSelected = project.Dataset.ResourcesData.Groups.Values.SingleOrDefault(item => item.Name == resGrp); if (resGrpSelected != null) { int resGrpId = resGrpSelected.Id; LightValue groupValue = new LightValue(resGroupes[resGrpId].Value, resGroupes[resGrpId].UnitExpression); if (groupValue.Dim == DimensionUtils.ENERGY) { rowString.Add(NiceValueWithAttribute(groupValue * amountRatio, preferedEnergy)); } else { rowString.Add(NiceValueWithAttribute(groupValue * amountRatio, preferedVolume)); } } else { rowString.Add("0"); } } } dt.Rows.Add(rowString.ToArray()); } #endregion #region wtp emissions foreach (string poll in pollutants) { rowString = new List <string>(); rowString.Add(poll + " (" + preferedMass + ")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); int polId = project.Dataset.GasesData.Values.Single(item => item.Name == poll).Id; rowString.Add(NiceValueWithAttribute( new LightValue(results.wellToProductEnem.emissions[polId], DimensionUtils.MASS) * amountRatio , preferedMass)); } dt.Rows.Add(rowString.ToArray()); } #endregion #region wtp Groups (here only GHG 100) foreach (string resGrp in polGroups) { rowString = new List <string>(); rowString.Add(resGrp + " (" + preferedMass + ")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); Dictionary <int, IValue> emGroupes = pair.Value[simulationYear].WellToProductEmissionsGroups(project.Dataset); Group resGrpSelected = project.Dataset.GasesData.Groups.Values.SingleOrDefault(item => item.Name == resGrp); if (resGrpSelected != null) { int grpId = resGrpSelected.Id; rowString.Add(NiceValueWithAttribute(new LightValue(emGroupes[grpId].Value, emGroupes[grpId].UnitExpression) * amountRatio, preferedMass)); } else { rowString.Add("0"); } } dt.Rows.Add(rowString.ToArray()); } #endregion #region urban emissions foreach (string poll in pollutants) { rowString = new List <string>(); rowString.Add("Urban " + poll + " (" + preferedMass + ")"); foreach (int simulationYear in pair.Value.Keys) { Results results = pair.Value[simulationYear]; double amountRatio = GetFunctionalRatio(project.Dataset, results, pair.Key.ResourceId); int polId = project.Dataset.GasesData.Values.Single(item => item.Name == poll).Id; rowString.Add(NiceValueWithAttribute(new LightValue(results.wellToProductUrbanEmission[polId], DimensionUtils.MASS) * amountRatio, preferedMass)); } dt.Rows.Add(rowString.ToArray()); } #endregion string value = ConvertDataTableToString(dt); System.IO.File.WriteAllText("Results-" + pair.Key.SourceType.ToString() + "-" + pair.Key.SourceMixOrPathwayID.ToString() + ".txt", value); } #endregion }
public abstract bool GetSFRValue(Bitmap bmp, ref SFRValue SFRValue, ref RectInfo rectInfo, Rectangle[] rectangles, ref LightValue lightValue, bool TestLight = false);
public void SetLight(int x, int y, int z, LightValue lightValue) { lightChunk[x, y, z] = lightValue; }