Caculators.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Linq;
  5. using Application.ATG_Classic_App.Model;
  6. namespace Application.ATG_Classic_App
  7. {
  8. public class HeightToVolumeCaculator
  9. {
  10. public enum Mode
  11. {
  12. /// <summary>
  13. /// when query height is not defined in profiles, the nearest(could be bigger or smaller) existed height value will be chosen for caculation.
  14. /// </summary>
  15. PreferNearest = 1,
  16. /// <summary>
  17. /// when query height is not defined in profiles, the next bigger value will be chosen for caculation.
  18. /// </summary>
  19. PreferCeiling = 2,
  20. /// <summary>
  21. /// when query height is not defined in profiles, the prior smaller value will be chosen for caculation.
  22. /// </summary>
  23. PreferFloor = 4,
  24. }
  25. public Mode EstimateMode { get; set; }
  26. private IOrderedEnumerable<TankProfileData> tankProfiles_by_Ascending;
  27. /// <summary>
  28. /// Default use EstimateMode = Mode.PreferNearest | Mode.PreferCeiling
  29. /// </summary>
  30. /// <param name="tankProfiles"></param>
  31. public HeightToVolumeCaculator(IEnumerable<TankProfileData> tankProfiles)
  32. {
  33. if (tankProfiles == null || !tankProfiles.Any()) throw new ArgumentNullException(nameof(tankProfiles));
  34. this.EstimateMode = Mode.PreferNearest | Mode.PreferCeiling;
  35. this.tankProfiles_by_Ascending = tankProfiles.OrderBy(p => p.Height);
  36. }
  37. public double GetVolume(double height)
  38. {
  39. var find = this.tankProfiles_by_Ascending.FirstOrDefault(p => p.Height == height);
  40. if (find != null) return find.Volume;
  41. TankProfileData estimation;
  42. if (this.EstimateMode.HasFlag(Mode.PreferNearest))
  43. {
  44. var next = this.tankProfiles_by_Ascending.FirstOrDefault(p => p.Height > height);
  45. if (next == null) return this.tankProfiles_by_Ascending.Last().Volume;
  46. var prior = this.tankProfiles_by_Ascending.LastOrDefault(p => p.Height < height);
  47. if (prior == null) return this.tankProfiles_by_Ascending.First().Volume;
  48. var offsetToNext = next.Height - height;
  49. var offsetToPrior = Math.Abs(prior.Height - height);
  50. if (offsetToNext < offsetToPrior)
  51. estimation = this.tankProfiles_by_Ascending.FirstOrDefault(p => p.Height == next.Height);
  52. else if (offsetToNext > offsetToPrior)
  53. estimation = this.tankProfiles_by_Ascending.FirstOrDefault(p => p.Height == prior.Height);
  54. else
  55. {
  56. if (this.EstimateMode.HasFlag(Mode.PreferCeiling))
  57. estimation = next;
  58. else
  59. estimation = prior;
  60. }
  61. }
  62. else if (this.EstimateMode == Mode.PreferCeiling)
  63. {
  64. // use the nearest up value for this query, so the queried volume would > real volume.
  65. estimation = this.tankProfiles_by_Ascending.FirstOrDefault(p => p.Height > height);
  66. if (estimation == null) return this.tankProfiles_by_Ascending.Last().Volume;
  67. }
  68. else if (this.EstimateMode == Mode.PreferFloor)
  69. {
  70. // use the nearest down value for this query, so the queried volume would < real volume.
  71. estimation = this.tankProfiles_by_Ascending.LastOrDefault(p => p.Height < height);
  72. if (estimation == null) return this.tankProfiles_by_Ascending.First().Volume;
  73. }
  74. else return 0;
  75. return estimation.Volume;
  76. }
  77. //public double GetTcVolume(double height)
  78. //{
  79. // return this.GetVolume(height);
  80. //}
  81. }
  82. public class TemperatureCompensationCaculator
  83. {
  84. private double coeff;
  85. /// <summary>
  86. ///
  87. /// </summary>
  88. /// <param name="expansionCoefficient">0.0007 is a typical value.</param>
  89. public TemperatureCompensationCaculator(double expansionCoefficient)
  90. {
  91. if (expansionCoefficient > 1 || expansionCoefficient < 0) throw new ArgumentException("invalid expansionCoefficient");
  92. this.coeff = expansionCoefficient;
  93. }
  94. /// <summary>
  95. /// Get the volume on standard temperature.
  96. /// </summary>
  97. /// <param name="standardTemp"></param>
  98. /// <param name="currentVol"></param>
  99. /// <param name="currentTemp"></param>
  100. /// <returns></returns>
  101. public double CaculateCompensatedVolume(double standardTemp, double currentVol, double currentTemp)
  102. {
  103. var volDiffPerLiter = 1 - this.coeff * (currentTemp - standardTemp);
  104. return volDiffPerLiter * currentVol;
  105. }
  106. }
  107. //public static class DeliveryDectector
  108. //{
  109. // /*according from Thomas.Gan: ATG will capture it as start delivery when it detect the product volume increase by >200 liter in the short period of time
  110. // * when the product has finish the delivery, the driver will wait for 15 minutes and go back to ATG console print out the latest tank slip.
  111. // * the driver will compare the volme before and after deliver and get the station staff to sign off
  112. // * on ATG, it will declar stop deivery when the product has not increase for the last 15 minutes
  113. // */
  114. // /* 1 meter squre = 1000L.
  115. // * in china, for one site, all tanks vol typically <=150000L, single tank <=50000L.
  116. // *
  117. // *
  118. // * by read a real site delivery reports with tank max vol 50000L, can get below facts:
  119. // * 需要记录,实发标准体积, 以V20温度计算,一般在15000L左右。
  120. // * each delivery vol amount is around 15000L.
  121. // *
  122. // */
  123. // private static MLContext mlContext;
  124. // public static DeviceProcessor.ATG.Delivery Get(IEnumerable<Model.Inventory> inventories)
  125. // {
  126. // IOrderedEnumerable<Model.Inventory> data = inventories.OrderBy(i => i.TimeStamp);
  127. // // Create MLContext to be shared across the model creation workflow objects
  128. // mlContext = new MLContext();
  129. // //assign the Number of records in dataset file to cosntant variable
  130. // int size = inventories.Count();
  131. // //Load the data into IDataView.
  132. // //This dataset is used while prediction/detecting spikes or changes.
  133. // IDataView dataView = mlContext.Data.LoadFromEnumerable<ProductInventoryData>(
  134. // data.Select(d =>
  135. // new ProductInventoryData() { TimeStamp = d.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss fff") }));
  136. // //To detech temporay changes in the pattern
  137. // //DetectSpike(size, dataView);
  138. // //To detect persistent change in the pattern
  139. // var predictions = DetectChangepoint(size, dataView).ToList();
  140. // for (int i = 0; i < predictions.Count(); i++)
  141. // {
  142. // if (predictions[i].Prediction[0] == 1)
  143. // {
  144. // //return new De
  145. // }
  146. // }
  147. // return null;
  148. // }
  149. // public class ProductInventoryData
  150. // {
  151. // public string TimeStamp;
  152. // public float Volume;
  153. // }
  154. // public class ProductInventoryPrediction
  155. // {
  156. // //vector to hold alert,score,p-value values
  157. // [VectorType(3)]
  158. // public double[] Prediction { get; set; }
  159. // }
  160. // static IEnumerable<ProductInventoryPrediction> DetectChangepoint(int size, IDataView dataView)
  161. // {
  162. // //Console.WriteLine("===============Detect Persistent changes in pattern===============");
  163. // //STEP 1: Setup transformations using DetectIidChangePoint
  164. // var estimator = mlContext.Transforms.DetectIidChangePoint(
  165. // outputColumnName: "Prediction",
  166. // inputColumnName: "Volume", confidence: 95, changeHistoryLength: size / 4);
  167. // //STEP 2:The Transformed Model.
  168. // //In IID Change point detection, we don't need need to do training, we just need to do transformation.
  169. // //As you are not training the model, there is no need to load IDataView with real data, you just need schema of data.
  170. // //So create empty data view and pass to Fit() method.
  171. // ITransformer tansformedModel = estimator.Fit(CreateEmptyDataView());
  172. // //STEP 3: Use/test model
  173. // //Apply data transformation to create predictions.
  174. // IDataView transformedData = tansformedModel.Transform(dataView);
  175. // var predictions = mlContext.Data.CreateEnumerable<ProductInventoryPrediction>(transformedData, reuseRowObject: false);
  176. // //Console.WriteLine($"{nameof(ProductInventoryPrediction.Prediction)} column obtained post-transformation.");
  177. // //Console.WriteLine("Alert\tScore\tP-Value\tMartingale value");
  178. // foreach (var p in predictions)
  179. // {
  180. // if (p.Prediction[0] == 1)
  181. // {
  182. // //Console.WriteLine("{0}\t{1:0.00}\t{2:0.00}\t{3:0.00} <-- alert is on, predicted changepoint",
  183. // // p.Prediction[0], p.Prediction[1], p.Prediction[2], p.Prediction[3]);
  184. // }
  185. // else
  186. // {
  187. // //Console.WriteLine("{0}\t{1:0.00}\t{2:0.00}\t{3:0.00}",
  188. // // p.Prediction[0], p.Prediction[1], p.Prediction[2], p.Prediction[3]);
  189. // }
  190. // }
  191. // //Console.WriteLine("");
  192. // return predictions;//.Select(p => p.Prediction[0] == 1);
  193. // }
  194. // private static IDataView CreateEmptyDataView()
  195. // {
  196. // //Create empty DataView. We just need the schema to call fit()
  197. // IEnumerable<ProductInventoryData> enumerableData = new List<ProductInventoryData>();
  198. // var dv = mlContext.Data.LoadFromEnumerable(enumerableData);
  199. // return dv;
  200. // }
  201. //}
  202. }