private static void LoadFromMethods(Type type) { MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { MathFunctionAttribute mfatt = method. GetCustomAttribute <MathFunctionAttribute>(); if (!method.IsStatic) { continue; } if (mfatt == null) { continue; } Delegate del = CreateDelegate(method); MathType ret = MathType.Boolean; try { ret = method.ReturnType.ToMathType(); } catch (ArgumentException) { continue; } List <MathType> args = new List <MathType>(); bool discard = false; foreach (ParameterInfo p in method.GetParameters()) { try { args.Add(p.ParameterType.ToMathType()); } catch (ArgumentException) { discard = true; break; } } if (discard) { Logger.Log(LogLevel.Warning, Logger.REGISTRY, "Argument found to be invalid for method " + method.Name + "(). Ignoring."); continue; } FunctionInfo func = new FunctionInfo(del, ret, mfatt.Name, args.ToArray()); Logger.Log(LogLevel.Debug, Logger.REGISTRY, "Registering function: " + func.Name); RegisterFunction(func); } }
/// <summary> /// Instantiates a new FunctionInfo /// </summary> public FunctionInfo(Delegate function, MathType ret, string name, params MathType[] args) { Function = function; ReturnType = ret; Name = name; ArgumentTypes = args.ToList(); }
public static double DoMath(double x, double y, MathType mathType) { double output = 0; switch (mathType) // switch statement { case MathType.Add: output = x + y; break; case MathType.Subtract: output = x - y; break; case MathType.Multiply: output = x * y; break; case MathType.Divide: output = x / y; break; default: throw new Exception("Bad info passed in"); } return(output); }
public static double DoMath(double x, double y, MathType mathType) { double output = 0; output = mathType switch { MathType.Add => x + y, MathType.Substract => x - y, MathType.Multiply => x * y, MathType.Divide => x / y, _ => throw new Exception("Bad info passed in") }; //switch (mathType) //{ // case MathType.Add: // output = x + y; // break; // case MathType.Substract: // output = x - y; // break; // case MathType.Multiply: // output = x * y; // break; // case MathType.Divide: // output = x / y; // break; // default: // throw new Exception("Bad info passed in"); //} return(output); }
public static double DoMath(double x, double y, MathType math) { double output; output = math switch { MathType.Add => x + y, MathType.Subtract => x - y, MathType.Multiply => x * y, MathType.Divide => x / y, _ => throw new Exception("Invalid Operation") }; //switch (math) //{ // case MathType.Add: // result = x + y; // break; // case MathType.Subtract: // result = x + y; // break; // case MathType.Multiply: // result = x + y; // break; // case MathType.Divide: // result = x + y; // break; // default: // throw new Exception("Invalid operation"); // break; //} return(output); } }
public static void SetTowerPrices(int modifier, MathType modifierType) { foreach (var tower in Game.instance.model.towers) { if (modifierType == MathType.Multiply) { tower.cost *= modifier; } else { tower.cost /= modifier; } } foreach (var upgrade in Game.instance.model.upgrades) { if (modifierType == MathType.Multiply) { upgrade.cost *= modifier; } else { upgrade.cost /= modifier; } } }
private TreeNode GetCalculatedNode(TreeNode operation, TreeNode firstArgument, TreeNode extraArgument = null) { MathType nodeType = operation.NodeType; if (nodeType is MathType.Comma) { return(GetCalculatedNode(operation.ParentNode, firstArgument, extraArgument)); } string oper = operation.Node; if (extraArgument != null) { oper = SwapOperExeption(operation, extraArgument); } double firstArg = firstArgument?.Value ?? throw new Exception("Error 11401910. Значение для узла не установлено"); double val = GetCalculatedValue(oper, firstArg, extraArgument?.Value ?? 0.0); var newNode = new TreeNode { ID = _mainIDCounter++, Node = val.ToString(CultureInfo.InvariantCulture), Value = val, NodeType = MathType.Constant, Child = new List <TreeNode>(), Position = -1, ParentNode = null, }; return(newNode); }
// Start is called before the first frame update public void init(MathType mathType, float speed) { this.speed = speed; this.mathType = mathType; switch (mathType) { case MathType.PLUS: plus(); break; case MathType.MINUS: minus(); break; case MathType.MULTIPLY: multiply(); break; case MathType.DIVIDE: divide(); break; default: plus(); Debug.Log("mathtype not implemented: " + mathType); break; } setText(); input.Select(); input.ActivateInputField(); }
//for use outside the slot public MathBox(MathType mathType) { this.mathType = mathType; this.hasHyperRepeatZones = false; base.Init(Player.NullPlayer); Setup(); }
/// <summary> /// Замена узла с сохранением ссылок на него из других источников. /// </summary> /// <param name="fromNode"></param> public void ReplaceBy(TreeNode fromNode) { ID = fromNode.ID; ParentNode = fromNode.ParentNode; Node = fromNode.Node; Value = fromNode.Value; NodeType = fromNode.NodeType; Child = fromNode.Child; Position = fromNode.Position; }
public MathBox(MathType mathType) //for use outside the slot { this.mathType = mathType; this.hasHyperRepeatZones = false; base.Init(Player.NullPlayer); Setup(); }
public MathBox(Slot slot, MathType mathType) { this.slot = slot; this.mathType = mathType; this.hasHyperRepeatZones = true; base.Init(slot.player); Setup(); }
public MathOperationManager(MathType type) { this.MathType = type; if (type == MathType.GPU) { this.globalInstance = new GpuMathOperations(); } else { this.globalInstance = new CpuMathOperations(); } }
public static double DoMath(double x, double y, MathType math) { double output = 0; output = math switch // switch expression { MathType.Add => x + y, MathType.Subtract => x - y, MathType.Multiply => x * y, MathType.Divide => x / y, _ => throw new Exception("Bad info passed in") }; return(output); } }
private int Emulate(int ldc, int ldc_, MathType mathType) { switch (mathType) { case MathType.Add: return(ldc + ldc_); case MathType.Min: return(ldc - ldc_); case MathType.Mul: return(ldc * ldc_); case MathType.Div: return(ldc / ldc_); default: return(0); } }
private System.Reflection.Emit.OpCode getOpCode(MathType mathType) { switch (mathType) { case MathType.Add: return(System.Reflection.Emit.OpCodes.Add); case MathType.Min: return(System.Reflection.Emit.OpCodes.Sub); case MathType.Mul: return(System.Reflection.Emit.OpCodes.Mul); case MathType.Div: return(System.Reflection.Emit.OpCodes.Div); default: return(System.Reflection.Emit.OpCodes.Add); } }
/// <summary> /// 保留小数位 /// </summary> /// <param name="obj">数量</param> /// <param name="len">保留小数位数</param> /// <param name="mathType">舍入类型</param> /// <returns></returns> public static decimal KeepDecimal(object obj, int len, MathType mathType = MathType.Round) { decimal result = Utils.ToDecimal(obj); switch (mathType) { case MathType.Floor: return(Math.Floor((decimal)Math.Pow(10, len) * result) / (decimal)Math.Pow(10, len)); case MathType.Ceil: return(Math.Ceiling((decimal)Math.Pow(10, len) * result) / (decimal)Math.Pow(10, len)); case MathType.Round: default: return(Math.Round(result, len, MidpointRounding.AwayFromZero)); } }
public static IMath GetMath(MathType mathType) { switch (mathType) { case MathType.Numbers: return(new Numbers()); case MathType.Decimal: return(new Decimal()); case MathType.Iota: return(new Iota()); default: throw new Exception("INvalid IMath"); } }
private void BuildTree(ref string word) { MathType wordType = MathTypeHlp.GetNodeType(word); switch (wordType) { case MathType.Constant: AddNode(wordType, word, ReadConst(word)); word = string.Empty; break; case MathType.Argument: AddNode(wordType, word); word = string.Empty; break; case MathType.EasyFunction: case MathType.MultiFunction: if (wordType is MathType.MultiFunction) { _isMoreThatOneArgFunc = true; } _parentNode = AddNode(wordType, word.Substring(0, 3)); word = word.Remove(0, 4); word = word.Remove(word.Length - 1, 1); break; case MathType.HightPrtOperator: case MathType.LowPrtOperator: case MathType.Comma: _parentNode = AddNode(wordType, word[1].ToString()); word = word.Remove(0, 2); break; case MathType.Home: throw new ArgumentOutOfRangeException(); default: throw new ArgumentOutOfRangeException(); } }
public TreeNode GetConstantNode(List <TreeNode> treeToFind, MathType sameTypeToFind) { foreach (TreeNode node in treeToFind) { if (IsConst(node) && node.ID != _nullNodeIndexSave) { return(node); } } //чтобы приоритет был у верхних листьев foreach (TreeNode node in treeToFind) { if (node.IsHaveChild && node.NodeType == sameTypeToFind) { return(GetConstantNode(node.Child, sameTypeToFind)); } } return(null); }
public static double DoMath(double x, double y, MathType math) { // Switch Expression double output = math switch { MathType.Add => x + y, MathType.Subtract => x - y, MathType.Multiply => x * y, MathType.Divide => x / y, _ => throw new Exception("Bad info passed in") }; // Switch Statement switch (math) { case MathType.Add: output = x + y; break; case MathType.Subtract: output = x - y; break; case MathType.Multiply: output = x * y; break; case MathType.Divide: output = x / y; break; default: throw new Exception("Bad info passed in"); } return(0); } }
/// <summary> /// Converts a MathTYpe to a System.Type. /// </summary> public static Type ToSystemType(this MathType mtype) { switch (mtype) { case MathType.Real: return(typeof(decimal)); case MathType.Integer: return(typeof(long)); case MathType.String: return(typeof(string)); case MathType.Boolean: return(typeof(bool)); case MathType.List: return(typeof(List <decimal>)); default: throw new ArgumentException("Not a valid MathType: " + mtype.ToString()); } }
private TreeNode AddNode(MathType wordType, string word = null, double?value = null) { var target = _parentNode; var position = 0; if (target.IsHaveChild) { position = 1; } var n = new TreeNode { ID = _mainIDCounter++, Node = word, Value = value, NodeType = wordType, Position = position, Child = new List <TreeNode>(), ParentNode = _parentNode }; target.Child.Add(n); return(n); }
public static double DoMath(double x, double y, MathType math) { double output = 0; // Switch statement //switch (math) //{ // case MathType.Add: // output = x + y; // break; // case MathType.Subtract: // output = x - y; // break; // case MathType.Multiply: // output = x * y; // break; // case MathType.Divide: // output = x / y; // break; // default: // throw new Exception("Bad info passed in"); //} // We can use Switch Expression instead if we want output = math switch { MathType.Add => x + y, MathType.Subtract => x - y, MathType.Multiply => x * y, MathType.Divide => x / y, _ => throw new Exception("Bad info passed in") }; return(output); } }
/// <summary> /// Sums the values of the items to the selected time interval and puts them in the new dfs file /// Assumes that the there are delete values at the same places in all items and timesteps! /// </summary> /// <param name="Items"></param> /// <param name="df"></param> /// <param name="SumTim"></param> public void TimeAggregation(int[] Items, DFSBase df, TimeInterval SumTim, int Tsteps, MathType mathtype) { //Initialize all items and fill the buffer with Deletevalues Dictionary <int, float[]> BufferData = new Dictionary <int, float[]>(); foreach (var j in Items) { BufferData[j] = new float[dfsdata.Count()]; for (int i = 0; i < dfsdata.Count(); i++) { BufferData[j][i] = (float)DeleteValue; } } DateTime LastPrint = TimeSteps[0]; bool PrintNow = false; int tstepCounter = 0; //Loop the time steps for (int i = 0; i < NumberOfTimeSteps; i++) { tstepCounter++; switch (SumTim) { case TimeInterval.Year: PrintNow = (LastPrint.Year + Tsteps == TimeSteps[i].Year); break; case TimeInterval.Month: int nextmonth = LastPrint.Month + Tsteps; if (nextmonth > 12) { nextmonth -= 12; } PrintNow = (nextmonth == TimeSteps[i].Month); break; case TimeInterval.Day: PrintNow = ((TimeSteps[i].Subtract(LastPrint) >= TimeSpan.FromDays(Tsteps))); break; default: break; } //Now print summed values and empty buffer if (PrintNow) { foreach (var j in Items) { if (mathtype == MathType.Average) //Average, and a division with the number of time steps is required { foreach (var n in NonDeleteIndex) { BufferData[j][n] = BufferData[j][n] / ((float)tstepCounter); } } if (df._timeAxis == TimeAxisType.CalendarNonEquidistant) { df.AppendTimeStep(df.TimeSteps.Last().AddDays(30)); } df.WriteItemTimeStep(df.NumberOfTimeSteps, j, BufferData[j]); //Reset buffer foreach (var n in NonDeleteIndex) { if (mathtype == MathType.Min) { BufferData[j][n] = float.MaxValue; } else if (mathtype == MathType.Max) { BufferData[j][n] = float.MinValue; } else { BufferData[j][n] = 0; } } } tstepCounter = 0; LastPrint = TimeSteps[i]; PrintNow = false; } //Sum all items foreach (var j in Items) { ReadItemTimeStep(i, j); if (i == 0) //fill initial values in buffer { foreach (var k in NonDeleteIndex) { if (mathtype == MathType.Min) { BufferData[j][k] = float.MaxValue; } else if (mathtype == MathType.Max) { BufferData[j][k] = float.MinValue; } else { BufferData[j][k] = 0; } } } var arr = BufferData[j]; foreach (int k in NonDeleteIndex) { if (mathtype == MathType.Min) { arr[k] = Math.Min(arr[k], dfsdata[k]); } else if (mathtype == MathType.Max) { arr[k] = Math.Max(arr[k], dfsdata[k]); } else { arr[k] += dfsdata[k]; } } } } //print the last summed values foreach (var j in Items) { if (mathtype == MathType.Average) //If not sum it is average and a division with the number of time steps is required { foreach (var n in NonDeleteIndex) { BufferData[j][n] = BufferData[j][n] / ((float)tstepCounter); } } df.WriteItemTimeStep(df.NumberOfTimeSteps, j, BufferData[j]); } }
private int Emulate(int ldc, ITypeDefOrRef type, MathType mathType) { return(Emulate(ldc, getLdc(type), mathType)); }
/// <summary> /// Does either summation or average on weekly, monthly or yearly basis /// </summary> /// <param name="OperationData"></param> /// <param name="sum"></param> private static void TimeAggregation(XElement OperationData, MathType mathtype) { DFS3.MaxEntriesInBuffer = 1; DFS2.MaxEntriesInBuffer = 1; string File1 = OperationData.Element("DFSFileName").Value; DFSBase dfs = DfsFileFactory.OpenFile(File1); int[] Items = ParseString(OperationData.Element("Items").Value, 1, dfs.Items.Count()); string timeinterval = OperationData.Element("TimeInterval").Value.ToLower(); var Tstep = OperationData.Element("TimeIntervalSteps"); int timesteps = 1; if (Tstep != null) timesteps = int.Parse(Tstep.Value); string File2; bool samefile = true; if (OperationData.Element("DFSOutputFileName") != null) { File2 = OperationData.Element("DFSOutputFileName").Value; samefile = false; } else { File2 = Path.Combine(Path.GetFileNameWithoutExtension(File1) + "_temp", Path.GetExtension(File1)); } DFSBase outfile = DfsFileFactory.CreateFile(File2, Items.Count()); outfile.CopyFromTemplate(dfs); int k = 0; //Create the items foreach (int j in Items) { int i = j - 1; outfile.Items[k].EumItem = dfs.Items[i].EumItem; outfile.Items[k].EumUnit = dfs.Items[i].EumUnit; outfile.Items[k].Name = dfs.Items[i].Name; k++; } switch (timeinterval) { case "month": outfile.TimeOfFirstTimestep = new DateTime(dfs.TimeOfFirstTimestep.Year, dfs.TimeOfFirstTimestep.Month, 15); outfile.TimeStep = TimeSpan.FromDays(365.0 / 12 * timesteps); dfs.TimeAggregation(Items, outfile, TimeInterval.Month, timesteps, mathtype); break; case "year": outfile.TimeOfFirstTimestep = new DateTime(dfs.TimeOfFirstTimestep.Year, 6, 1); outfile.TimeStep = TimeSpan.FromDays(365.0 * timesteps); dfs.TimeAggregation(Items, outfile, TimeInterval.Year, timesteps, mathtype); break; case "day": outfile.TimeStep = TimeSpan.FromDays(timesteps); dfs.TimeAggregation(Items, outfile, TimeInterval.Day, timesteps, mathtype); break; default: break; } //Close the files dfs.Dispose(); outfile.Dispose(); if (samefile) { File.Delete(File1); FileInfo f = new FileInfo(File2); File.Move(File2, File1); } }
public static List <LogInfo> Math(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_Math)); CodeInfo_Math info = cmd.Info as CodeInfo_Math; MathType type = info.Type; switch (type) { case MathType.Add: case MathType.Sub: case MathType.Mul: case MathType.Div: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_Arithmetic)); MathInfo_Arithmetic subInfo = info.SubInfo as MathInfo_Arithmetic; string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); if (!NumberHelper.ParseDecimal(srcStr1, out decimal src1)) { throw new ExecuteException($"[{srcStr1}] is not a valid integer"); } if (!NumberHelper.ParseDecimal(srcStr2, out decimal src2)) { throw new ExecuteException($"[{srcStr2}] is not a valid integer"); } decimal destInt; if (type == MathType.Add) { destInt = src1 + src2; } else if (type == MathType.Sub) { destInt = src1 - src2; } else if (type == MathType.Mul) { destInt = src1 * src2; } else if (type == MathType.Div) { destInt = src1 / src2; } else { throw new InternalException($"Internal Logic Error at Math,Arithmetic"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destInt.ToString())); } break; case MathType.IntDiv: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_IntDiv)); MathInfo_IntDiv subInfo = info.SubInfo as MathInfo_IntDiv; string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); if (srcStr1.StartsWith("-", StringComparison.Ordinal) || srcStr2.StartsWith("-", StringComparison.Ordinal)) { // Signed if (!NumberHelper.ParseInt64(srcStr1, out long src1)) { throw new ExecuteException($"[{srcStr1}] is not a valid integer"); } if (!NumberHelper.ParseInt64(srcStr2, out long src2)) { throw new ExecuteException($"[{srcStr2}] is not a valid integer"); } long q = src1 / src2; long r = src1 % src2; logs.AddRange(Variables.SetVariable(s, subInfo.QuotientVar, q.ToString())); logs.AddRange(Variables.SetVariable(s, subInfo.RemainderVar, r.ToString())); } else { // Unsigned if (!NumberHelper.ParseUInt64(srcStr1, out ulong src1)) { throw new ExecuteException($"[{srcStr1}] is not a valid integer"); } if (!NumberHelper.ParseUInt64(srcStr2, out ulong src2)) { throw new ExecuteException($"[{srcStr2}] is not a valid integer"); } ulong q = src1 / src2; ulong r = src1 % src2; logs.AddRange(Variables.SetVariable(s, subInfo.QuotientVar, q.ToString())); logs.AddRange(Variables.SetVariable(s, subInfo.RemainderVar, r.ToString())); } } break; case MathType.Neg: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_Neg)); MathInfo_Neg subInfo = info.SubInfo as MathInfo_Neg; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (!NumberHelper.ParseDecimal(srcStr, out decimal src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } decimal destInt = (src * -1); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destInt.ToString())); } break; case MathType.ToSign: case MathType.ToUnsign: { // Math,IntSign,<DestVar>,<Src>,[8|16|32|64] // Math,IntUnsign,<DestVar>,<Src>,[8|16|32|64] Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_IntegerSignedness)); MathInfo_IntegerSignedness subInfo = info.SubInfo as MathInfo_IntegerSignedness; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); string destStr; if (info.Type == MathType.ToSign) { // Unsigned int to signed int switch (subInfo.BitSize) { case 8: { if (!NumberHelper.ParseUInt8(srcStr, out byte src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((sbyte)src).ToString(); } break; case 16: { if (!NumberHelper.ParseUInt16(srcStr, out ushort src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((short)src).ToString(); } break; case 32: { if (!NumberHelper.ParseUInt32(srcStr, out uint src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((int)src).ToString(); } break; case 64: { if (!NumberHelper.ParseUInt64(srcStr, out ulong src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((long)src).ToString(); } break; default: throw new InternalException($"Internal Logic Error at Math,ToSign"); } } else { // Signed int to unsigned int switch (subInfo.BitSize) { case 8: { if (!NumberHelper.ParseInt8(srcStr, out sbyte src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((byte)src).ToString(); } break; case 16: { if (!NumberHelper.ParseInt16(srcStr, out short src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((ushort)src).ToString(); } break; case 32: { if (!NumberHelper.ParseInt32(srcStr, out int src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((uint)src).ToString(); } break; case 64: { if (!NumberHelper.ParseInt64(srcStr, out long src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((ulong)src).ToString(); } break; default: throw new InternalException($"Internal Logic Error at Math,ToUnsign"); } } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.BoolAnd: case MathType.BoolOr: case MathType.BoolXor: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_BoolLogicOper)); MathInfo_BoolLogicOper subInfo = info.SubInfo as MathInfo_BoolLogicOper; string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); bool src1 = false; if (srcStr1.Equals("True", StringComparison.OrdinalIgnoreCase)) { src1 = true; } else if (!srcStr1.Equals("False", StringComparison.OrdinalIgnoreCase)) { throw new ExecuteException($"[{srcStr1}] is not valid boolean value"); } bool src2 = false; if (srcStr2.Equals("True", StringComparison.OrdinalIgnoreCase)) { src2 = true; } else if (!srcStr2.Equals("False", StringComparison.OrdinalIgnoreCase)) { throw new ExecuteException($"[{srcStr2}] is not valid boolean value"); } bool dest; if (type == MathType.BoolAnd) { dest = src1 && src2; } else if (type == MathType.BoolOr) { dest = src1 || src2; } else if (type == MathType.BoolXor) { dest = src1 ^ src2; } else { throw new InternalException($"Internal Logic Error at Math,BoolLogicOper"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString())); } break; case MathType.BoolNot: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_BoolNot)); MathInfo_BoolNot subInfo = info.SubInfo as MathInfo_BoolNot; bool src = false; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (srcStr.Equals("True", StringComparison.OrdinalIgnoreCase)) { src = true; } else if (!srcStr.Equals("False", StringComparison.OrdinalIgnoreCase)) { throw new ExecuteException($"[{srcStr}] is not valid boolean value"); } bool dest = !src; logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString())); } break; case MathType.BitAnd: case MathType.BitOr: case MathType.BitXor: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_BitLogicOper)); MathInfo_BitLogicOper subInfo = info.SubInfo as MathInfo_BitLogicOper; string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); if (!NumberHelper.ParseUInt64(srcStr1, out ulong src1)) { throw new ExecuteException($"[{srcStr1}] is not a valid integer"); } if (!NumberHelper.ParseUInt64(srcStr2, out ulong src2)) { throw new ExecuteException($"[{srcStr2}] is not a valid integer"); } ulong dest; if (type == MathType.BitAnd) { dest = src1 & src2; } else if (type == MathType.BitOr) { dest = src1 | src2; } else if (type == MathType.BitXor) { dest = src1 ^ src2; } else { throw new InternalException($"Internal Logic Error at Math,BitLogicOper"); } string destStr = dest.ToString(); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.BitNot: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_BitNot)); MathInfo_BitNot subInfo = info.SubInfo as MathInfo_BitNot; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); string destStr; switch (subInfo.BitSize) { case 8: { if (!NumberHelper.ParseUInt8(srcStr, out byte src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((byte)(~src)).ToString(); } break; case 16: { if (!NumberHelper.ParseUInt16(srcStr, out ushort src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((ushort)(~src)).ToString(); } break; case 32: { if (!NumberHelper.ParseUInt32(srcStr, out uint src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((uint)(~src)).ToString(); } break; case 64: { if (!NumberHelper.ParseUInt64(srcStr, out ulong src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } destStr = ((ulong)(~src)).ToString(); } break; default: throw new InternalException($"Internal Logic Error at Math,BitNot"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.BitShift: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_BitShift)); MathInfo_BitShift subInfo = info.SubInfo as MathInfo_BitShift; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); string shiftStr = StringEscaper.Preprocess(s, subInfo.Shift); if (!NumberHelper.ParseInt32(shiftStr, out int shift)) { throw new ExecuteException($"[{shiftStr}] is not a valid integer"); } string leftRightStr = StringEscaper.Preprocess(s, subInfo.LeftRight); bool isLeft = false; if (leftRightStr.Equals("Left", StringComparison.OrdinalIgnoreCase)) { isLeft = true; } else if (!leftRightStr.Equals("Right", StringComparison.OrdinalIgnoreCase)) { throw new ExecuteException($"[{leftRightStr}] must be one of [Left, Right]"); } string destStr; switch (subInfo.BitSize) { case 8: { if (!NumberHelper.ParseUInt8(srcStr, out byte src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } byte dest; if (isLeft) { dest = (byte)(src << shift); } else { dest = (byte)(src >> shift); } destStr = dest.ToString(); } break; case 16: { if (!NumberHelper.ParseUInt16(srcStr, out ushort src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } ushort dest; if (isLeft) { dest = (ushort)(src << shift); } else { dest = (ushort)(src >> shift); } destStr = dest.ToString(); } break; case 32: { if (!NumberHelper.ParseUInt32(srcStr, out uint src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } uint dest; if (isLeft) { dest = (uint)(src << shift); } else { dest = (uint)(src >> shift); } destStr = dest.ToString(); } break; case 64: { if (!NumberHelper.ParseUInt64(srcStr, out ulong src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } ulong dest; if (isLeft) { dest = (ulong)(src << shift); } else { dest = (ulong)(src >> shift); } destStr = dest.ToString(); } break; default: throw new InternalException($"Internal Logic Error at Math,BitShift"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.Ceil: case MathType.Floor: case MathType.Round: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_CeilFloorRound)); MathInfo_CeilFloorRound subInfo = info.SubInfo as MathInfo_CeilFloorRound; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (!NumberHelper.ParseInt64(srcStr, out long srcInt)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } string unitStr = StringEscaper.Preprocess(s, subInfo.Unit); // Is roundToStr number? if (!NumberHelper.ParseInt64(unitStr, out long unit)) { throw new ExecuteException($"[{unitStr}] is not a valid integer"); } if (unit < 0) { throw new ExecuteException($"[{unit}] must be positive integer"); } long destInt; long remainder = srcInt % unit; if (type == MathType.Ceil) { destInt = srcInt - remainder + unit; } else if (type == MathType.Floor) { destInt = srcInt - remainder; } else // if (type == StrFormatType.Round) { if ((unit - 1) / 2 < remainder) { destInt = srcInt - remainder + unit; } else { destInt = srcInt - remainder; } } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destInt.ToString()); logs.AddRange(varLogs); } break; case MathType.Abs: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_Abs)); MathInfo_Abs subInfo = info.SubInfo as MathInfo_Abs; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (!NumberHelper.ParseDecimal(srcStr, out decimal src)) { throw new ExecuteException($"[{srcStr}] is not a valid integer"); } decimal dest = System.Math.Abs(src); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString())); } break; case MathType.Pow: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_Pow)); MathInfo_Pow subInfo = info.SubInfo as MathInfo_Pow; string baseStr = StringEscaper.Preprocess(s, subInfo.Base); if (!NumberHelper.ParseDecimal(baseStr, out decimal _base)) { throw new ExecuteException($"[{baseStr}] is not a valid integer"); } string powerStr = StringEscaper.Preprocess(s, subInfo.Power); if (!NumberHelper.ParseUInt32(powerStr, out uint power)) { throw new ExecuteException($"[{baseStr}] is not a postivie integer"); } decimal dest = NumberHelper.DecimalPower(_base, power); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString())); } break; case MathType.Hex: { Debug.Assert(info.SubInfo.GetType() == typeof(MathInfo_Hex)); MathInfo_Hex subInfo = info.SubInfo as MathInfo_Hex; string intStr = StringEscaper.Preprocess(s, subInfo.Integer); string dest; switch (subInfo.BitSize) { case 8: if (!NumberHelper.ParseSignedUInt8(intStr, out byte u8)) { throw new ExecuteException($"[{intStr}] is not a valid 8bit integer"); } dest = u8.ToString("X2"); break; case 16: if (!NumberHelper.ParseSignedUInt16(intStr, out ushort u16)) { throw new ExecuteException($"[{intStr}] is not a valid 16bit integer"); } dest = u16.ToString("X4"); break; case 32: if (!NumberHelper.ParseSignedUInt32(intStr, out uint u32)) { throw new ExecuteException($"[{intStr}] is not a valid 32bit integer"); } dest = u32.ToString("X8"); break; case 64: if (!NumberHelper.ParseSignedUInt64(intStr, out ulong u64)) { throw new ExecuteException($"[{intStr}] is not a valid 64bit integer"); } dest = u64.ToString("X16"); break; default: throw new InternalException($"Internal Logic Error at Math,Hex"); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, dest); logs.AddRange(varLogs); } break; default: // Error throw new InvalidCodeCommandException($"Wrong MathType [{type}]"); } return(logs); }
public MathToken(MathType type) { _type = type; }
public MathPass(MathType type) { _type = type; }
private string GetOpName(MathType type) { switch (type) { case MathType.Add: return "op_Addition"; case MathType.Divide: return "op_Division"; case MathType.Modulus: return "op_Modulus"; case MathType.Multiply: return "op_Multiply"; case MathType.Subtract: return "op_Subtraction"; } return ""; }
private string GetOpCode(MathType type) { switch (type) { case MathType.Add: return "+"; case MathType.Divide: return "/"; case MathType.Modulus: return "%"; case MathType.Multiply: return "*"; case MathType.Subtract: return "-"; } return ""; }
/// <summary> /// 加纵向比例 /// </summary> /// <param name="values"></param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns></returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { ObsDoubles vls = values[0] as ObsDoubles; Well owner = values[1] as Well; if (vls == null || owner == null) { return(null); } if (owner.Depths.Count != vls.Count) { return(null); } if (vls.Count <= 1) { return(null); } double mindepth = owner.Depths[0]; double[] validValueList = vls.Select(s => s).Where(s => (s != InvalidValue)).ToArray();//从曲线数组中去除无效值,形成有效值数组 double xMin = validValueList.Min(); double xMax = validValueList.Max(); // 曲线在使用对数时,抽稀算法无法抽稀出数据,暂时都用线性的 2017-4-7 MathType mathType = (MathType)values[2]; if (mathType == MathType.DEFAULT) { if (xMax - xMin > 60) { mathType = MathType.LINER; } else { mathType = MathType.LINER; } } PathGeometry geom = new PathGeometry(); double StartY = (owner.Depths[vls.ToList().IndexOf(validValueList[0])] - mindepth) * Enums.PerMilePx / owner.LongitudinalProportion; // 计算StartPoint的Y值,Y值为第一个有效值的深度,X值为最小值,保证闭合时连线为直线 double EndY = (owner.Depths[vls.ToList().LastIndexOf(validValueList[validValueList.Length - 1])] - mindepth) * Enums.PerMilePx / owner.LongitudinalProportion; // 增加一个结束点,Y值为最后一个有效值的深度,X值为最小值,保证闭合时连线为直线 gTopology.PointList pointlist = new gTopology.PointList(); pointlist.Add(new Point() { X = 0, Y = StartY }); for (int i = 0; i < vls.Count; ++i) { if (vls[i] == InvalidValue) { continue; } else { double x = (vls[i] - xMin) * 60 / (xMax - xMin); // 横向比例默认为 (曲线最小值-曲线最大值),60代表道宽 if (mathType.Equals(Enums.MathType.ARITHM)) { x = Math.Log10(vls[i]) - Math.Log10(xMin); } double yValue = (owner.Depths[i] - mindepth) * Enums.PerMilePx / owner.LongitudinalProportion;//根据纵向比例,计算出Y值 pointlist.Add(new Point() { X = x, Y = yValue }); } } pointlist.Add(new Point() { X = 0, Y = EndY }); gTopology.PointList plist = gTopology.SimpleLine.Simplifier(pointlist, 1); PathFigure figure = new PathFigure() { StartPoint = plist[0], IsClosed = true }; PointCollection pc = new PointCollection(plist.GetRange(1, plist.Count - 1)); PolyLineSegment pls = new PolyLineSegment() { Points = pc }; figure.Segments.Add(pls); geom.Figures.Add(figure); return(geom); }
/// <summary> /// Sums the values of the items to the selected time interval and puts them in the new dfs file /// Assumes that the there are delete values at the same places in all items and timesteps! /// </summary> /// <param name="Items"></param> /// <param name="df"></param> /// <param name="SumTim"></param> public void TimeAggregation(int[] Items, DFSBase df, TimeInterval SumTim, int Tsteps, MathType mathtype) { //Initialize all items and fill the buffer with Deletevalues Dictionary<int, float[]> BufferData = new Dictionary<int, float[]>(); foreach (var j in Items) { BufferData[j] = new float[dfsdata.Count()]; for (int i = 0; i < dfsdata.Count(); i++) BufferData[j][i] = (float)DeleteValue; } DateTime LastPrint = TimeSteps[0]; bool PrintNow = false; int tstepCounter = 0; //Loop the time steps for (int i = 0; i < NumberOfTimeSteps; i++) { tstepCounter++; switch (SumTim) { case TimeInterval.Year: PrintNow = (LastPrint.Year + Tsteps == TimeSteps[i].Year); break; case TimeInterval.Month: int nextmonth = LastPrint.Month + Tsteps; if (nextmonth > 12) nextmonth -= 12; PrintNow = (nextmonth == TimeSteps[i].Month); break; case TimeInterval.Day: PrintNow = ((TimeSteps[i].Subtract(LastPrint) >= TimeSpan.FromDays(Tsteps))); break; default: break; } //Now print summed values and empty buffer if (PrintNow) { foreach (var j in Items) { if (mathtype== MathType.Average) //Average, and a division with the number of time steps is required foreach (var n in NonDeleteIndex) BufferData[j][n] = BufferData[j][n] / ((float)tstepCounter); if (df._timeAxis == TimeAxisType.CalendarNonEquidistant) df.AppendTimeStep(df.TimeSteps.Last().AddDays(30)); df.WriteItemTimeStep(df.NumberOfTimeSteps, j, BufferData[j]); //Reset buffer foreach (var n in NonDeleteIndex) if (mathtype == MathType.Min) BufferData[j][n] = float.MaxValue; else if (mathtype == MathType.Max) BufferData[j][n] = float.MinValue; else BufferData[j][n] = 0; } tstepCounter = 0; LastPrint = TimeSteps[i]; PrintNow = false; } //Sum all items foreach (var j in Items) { ReadItemTimeStep(i, j); if (i == 0) //fill initial values in buffer { foreach (var k in NonDeleteIndex) { if (mathtype == MathType.Min) BufferData[j][k] = float.MaxValue; else if (mathtype == MathType.Max) BufferData[j][k] = float.MinValue; else BufferData[j][k] = 0; } } var arr = BufferData[j]; foreach (int k in NonDeleteIndex) if (mathtype == MathType.Min) arr[k] = Math.Min(arr[k], dfsdata[k]); else if (mathtype == MathType.Max) arr[k] = Math.Max(arr[k], dfsdata[k]); else arr[k] += dfsdata[k]; } } //print the last summed values foreach (var j in Items) { if (mathtype == MathType.Average) //If not sum it is average and a division with the number of time steps is required foreach (var n in NonDeleteIndex) BufferData[j][n] = BufferData[j][n] / ((float)tstepCounter); df.WriteItemTimeStep(df.NumberOfTimeSteps, j, BufferData[j]); } }
public static List <LogInfo> Math(EngineState s, CodeCommand cmd) { List <LogInfo> logs = new List <LogInfo>(); CodeInfo_Math info = cmd.Info.Cast <CodeInfo_Math>(); MathType type = info.Type; switch (type) { case MathType.Add: case MathType.Sub: case MathType.Mul: case MathType.Div: { MathInfo_Arithmetic subInfo = info.SubInfo.Cast <MathInfo_Arithmetic>(); string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); if (!NumberHelper.ParseDecimal(srcStr1, out decimal src1)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr1}] is not a valid integer")); } if (!NumberHelper.ParseDecimal(srcStr2, out decimal src2)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr2}] is not a valid integer")); } decimal destInt; switch (type) { case MathType.Add: destInt = src1 + src2; break; case MathType.Sub: destInt = src1 - src2; break; case MathType.Mul: destInt = src1 * src2; break; case MathType.Div: destInt = src1 / src2; break; default: throw new InternalException("Internal Logic Error at Math,Arithmetic"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destInt.ToString(CultureInfo.InvariantCulture))); } break; case MathType.IntDiv: { MathInfo_IntDiv subInfo = info.SubInfo.Cast <MathInfo_IntDiv>(); string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); if (srcStr1.StartsWith("-", StringComparison.Ordinal) || srcStr2.StartsWith("-", StringComparison.Ordinal)) { // Signed if (!NumberHelper.ParseInt64(srcStr1, out long src1)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr1}] is not a valid integer")); } if (!NumberHelper.ParseInt64(srcStr2, out long src2)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr2}] is not a valid integer")); } long q = src1 / src2; long r = src1 % src2; logs.AddRange(Variables.SetVariable(s, subInfo.QuotientVar, q.ToString())); logs.AddRange(Variables.SetVariable(s, subInfo.RemainderVar, r.ToString())); } else { // Unsigned if (!NumberHelper.ParseUInt64(srcStr1, out ulong src1)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr1}] is not a valid integer")); } if (!NumberHelper.ParseUInt64(srcStr2, out ulong src2)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr2}] is not a valid integer")); } ulong q = src1 / src2; ulong r = src1 % src2; logs.AddRange(Variables.SetVariable(s, subInfo.QuotientVar, q.ToString())); logs.AddRange(Variables.SetVariable(s, subInfo.RemainderVar, r.ToString())); } } break; case MathType.Neg: { MathInfo_Neg subInfo = info.SubInfo.Cast <MathInfo_Neg>(); string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (!NumberHelper.ParseDecimal(srcStr, out decimal src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } decimal destInt = src * -1; logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destInt.ToString(CultureInfo.InvariantCulture))); } break; case MathType.ToSign: case MathType.ToUnsign: { // Math,IntSign,<DestVar>,<Src>,<BitSize> // Math,IntUnsign,<DestVar>,<Src>,<BitSize> MathInfo_IntegerSignedness subInfo = info.SubInfo.Cast <MathInfo_IntegerSignedness>(); string srcStr = StringEscaper.Preprocess(s, subInfo.Src); string bitSizeStr = StringEscaper.Preprocess(s, subInfo.BitSize); string errorMsg = ParseAndCheckBitSize(bitSizeStr, out int bitSize); if (errorMsg != null) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string destStr; if (info.Type == MathType.ToSign) { // Unsigned int to signed int switch (bitSize) { case 8: { if (!NumberHelper.ParseUInt8(srcStr, out byte src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((sbyte)src).ToString(); } break; case 16: { if (!NumberHelper.ParseUInt16(srcStr, out ushort src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((short)src).ToString(); } break; case 32: { if (!NumberHelper.ParseUInt32(srcStr, out uint src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((int)src).ToString(); } break; case 64: { if (!NumberHelper.ParseUInt64(srcStr, out ulong src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((long)src).ToString(); } break; default: throw new InternalException("Internal Logic Error at Math,ToSign"); } } else { // Signed int to unsigned int switch (bitSize) { case 8: { if (!NumberHelper.ParseInt8(srcStr, out sbyte src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((byte)src).ToString(); } break; case 16: { if (!NumberHelper.ParseInt16(srcStr, out short src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((ushort)src).ToString(); } break; case 32: { if (!NumberHelper.ParseInt32(srcStr, out int src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((uint)src).ToString(); } break; case 64: { if (!NumberHelper.ParseInt64(srcStr, out long src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((ulong)src).ToString(); } break; default: throw new InternalException("Internal Logic Error at Math,ToUnsign"); } } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.BoolAnd: case MathType.BoolOr: case MathType.BoolXor: { MathInfo_BoolLogicOperation subInfo = info.SubInfo.Cast <MathInfo_BoolLogicOperation>(); string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); bool src1; if (NumberHelper.ParseInt64(srcStr1, out long srcInt1)) // C-Style Boolean { src1 = srcInt1 != 0; } else if (srcStr1.Equals("True", StringComparison.OrdinalIgnoreCase)) { src1 = true; } else if (srcStr1.Equals("False", StringComparison.OrdinalIgnoreCase)) { src1 = false; } else { return(LogInfo.LogErrorMessage(logs, $"[{srcStr1}] is not valid boolean value")); } bool src2; if (NumberHelper.ParseInt64(srcStr2, out long srcInt2)) // C-Style Boolean { src2 = srcInt2 != 0; } else if (srcStr2.Equals("True", StringComparison.OrdinalIgnoreCase)) { src2 = true; } else if (srcStr2.Equals("False", StringComparison.OrdinalIgnoreCase)) { src2 = false; } else { return(LogInfo.LogErrorMessage(logs, $"[{srcStr2}] is not valid boolean value")); } bool dest; switch (type) { case MathType.BoolAnd: dest = src1 && src2; break; case MathType.BoolOr: dest = src1 || src2; break; case MathType.BoolXor: dest = src1 ^ src2; break; default: throw new InternalException("Internal Logic Error at Math,BoolLogicOper"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString())); } break; case MathType.BoolNot: { MathInfo_BoolNot subInfo = info.SubInfo.Cast <MathInfo_BoolNot>(); bool src; string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (NumberHelper.ParseInt64(srcStr, out long srcInt)) // C-Style Boolean { src = srcInt != 0; } else if (srcStr.Equals("True", StringComparison.OrdinalIgnoreCase)) { src = true; } else if (srcStr.Equals("False", StringComparison.OrdinalIgnoreCase)) { src = false; } else { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not valid boolean value")); } bool dest = !src; logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString())); } break; case MathType.BitAnd: case MathType.BitOr: case MathType.BitXor: { MathInfo_BitLogicOperation subInfo = info.SubInfo.Cast <MathInfo_BitLogicOperation>(); string srcStr1 = StringEscaper.Preprocess(s, subInfo.Src1); string srcStr2 = StringEscaper.Preprocess(s, subInfo.Src2); if (!NumberHelper.ParseUInt64(srcStr1, out ulong src1)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr1}] is not a valid integer")); } if (!NumberHelper.ParseUInt64(srcStr2, out ulong src2)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr2}] is not a valid integer")); } ulong dest; switch (type) { case MathType.BitAnd: dest = src1 & src2; break; case MathType.BitOr: dest = src1 | src2; break; case MathType.BitXor: dest = src1 ^ src2; break; default: throw new InternalException("Internal Logic Error at Math,BitLogicOper"); } string destStr = dest.ToString(); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.BitNot: { MathInfo_BitNot subInfo = info.SubInfo.Cast <MathInfo_BitNot>(); string srcStr = StringEscaper.Preprocess(s, subInfo.Src); string bitSizeStr = StringEscaper.Preprocess(s, subInfo.BitSize); string errorMsg = ParseAndCheckBitSize(bitSizeStr, out int bitSize); if (errorMsg != null) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string destStr; switch (bitSize) { case 8: { if (!NumberHelper.ParseUInt8(srcStr, out byte src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((byte)~src).ToString(); } break; case 16: { if (!NumberHelper.ParseUInt16(srcStr, out ushort src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = ((ushort)~src).ToString(); } break; case 32: { if (!NumberHelper.ParseUInt32(srcStr, out uint src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = (~src).ToString(); } break; case 64: { if (!NumberHelper.ParseUInt64(srcStr, out ulong src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } destStr = (~src).ToString(); } break; default: throw new InternalException("Internal Logic Error at Math,BitNot"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.BitShift: { MathInfo_BitShift subInfo = info.SubInfo.Cast <MathInfo_BitShift>(); string srcStr = StringEscaper.Preprocess(s, subInfo.Src); string shiftStr = StringEscaper.Preprocess(s, subInfo.Shift); if (!NumberHelper.ParseInt32(shiftStr, out int shift)) { return(LogInfo.LogErrorMessage(logs, $"[{shiftStr}] is not a valid integer")); } string directionStr = StringEscaper.Preprocess(s, subInfo.Direction); bool isLeft = false; if (directionStr.Equals("Left", StringComparison.OrdinalIgnoreCase)) { isLeft = true; } else if (!directionStr.Equals("Right", StringComparison.OrdinalIgnoreCase)) { return(LogInfo.LogErrorMessage(logs, $"[{directionStr}] must be one of [Left, Right]")); } string bitSizeStr = StringEscaper.Preprocess(s, subInfo.BitSize); string errorMsg = ParseAndCheckBitSize(bitSizeStr, out int bitSize); if (errorMsg != null) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string destStr; switch (bitSize) { case 8: { if (!NumberHelper.ParseUInt8(srcStr, out byte src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } byte dest; if (isLeft) { dest = (byte)(src << shift); } else { dest = (byte)(src >> shift); } destStr = dest.ToString(); } break; case 16: { if (!NumberHelper.ParseUInt16(srcStr, out ushort src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } ushort dest; if (isLeft) { dest = (ushort)(src << shift); } else { dest = (ushort)(src >> shift); } destStr = dest.ToString(); } break; case 32: { if (!NumberHelper.ParseUInt32(srcStr, out uint src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } uint dest; if (isLeft) { dest = src << shift; } else { dest = src >> shift; } destStr = dest.ToString(); } break; case 64: { if (!NumberHelper.ParseUInt64(srcStr, out ulong src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } ulong dest; if (isLeft) { dest = src << shift; } else { dest = src >> shift; } destStr = dest.ToString(); } break; default: throw new InternalException("Internal Logic Error at Math,BitShift"); } logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, destStr)); } break; case MathType.Ceil: case MathType.Floor: case MathType.Round: { MathInfo_CeilFloorRound subInfo = info.SubInfo.Cast <MathInfo_CeilFloorRound>(); string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (!NumberHelper.ParseInt64(srcStr, out long srcInt)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } string unitStr = StringEscaper.Preprocess(s, subInfo.Unit); // Is roundToStr number? if (!NumberHelper.ParseInt64(unitStr, out long unit)) { return(LogInfo.LogErrorMessage(logs, $"[{unitStr}] is not a valid integer")); } if (unit < 0) { return(LogInfo.LogErrorMessage(logs, $"[{unit}] must be positive integer")); } long destInt; long remainder = srcInt % unit; switch (type) { case MathType.Ceil: destInt = srcInt - remainder + unit; break; case MathType.Floor: destInt = srcInt - remainder; break; case MathType.Round: if ((unit - 1) / 2 < remainder) { destInt = srcInt - remainder + unit; } else { destInt = srcInt - remainder; } break; default: throw new InternalException($"Internal Logic Error at Math,{info.Type}"); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destInt.ToString()); logs.AddRange(varLogs); } break; case MathType.Abs: { MathInfo_Abs subInfo = info.SubInfo.Cast <MathInfo_Abs>(); string srcStr = StringEscaper.Preprocess(s, subInfo.Src); if (!NumberHelper.ParseDecimal(srcStr, out decimal src)) { return(LogInfo.LogErrorMessage(logs, $"[{srcStr}] is not a valid integer")); } decimal dest = System.Math.Abs(src); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString(CultureInfo.InvariantCulture))); } break; case MathType.Pow: { MathInfo_Pow subInfo = info.SubInfo.Cast <MathInfo_Pow>(); string baseStr = StringEscaper.Preprocess(s, subInfo.Base); if (!NumberHelper.ParseDecimal(baseStr, out decimal _base)) { return(LogInfo.LogErrorMessage(logs, $"[{baseStr}] is not a valid integer")); } string powerStr = StringEscaper.Preprocess(s, subInfo.Power); if (!NumberHelper.ParseUInt32(powerStr, out uint power)) { return(LogInfo.LogErrorMessage(logs, $"[{baseStr}] is not a postivie integer")); } decimal dest = NumberHelper.DecimalPower(_base, power); logs.AddRange(Variables.SetVariable(s, subInfo.DestVar, dest.ToString(CultureInfo.InvariantCulture))); } break; case MathType.Hex: case MathType.Dec: { MathInfo_HexDec subInfo = info.SubInfo.Cast <MathInfo_HexDec>(); string intStr = StringEscaper.Preprocess(s, subInfo.Src); string bitSizeStr = StringEscaper.Preprocess(s, subInfo.BitSize); string errorMsg = ParseAndCheckBitSize(bitSizeStr, out int bitSize); if (errorMsg != null) { return(LogInfo.LogErrorMessage(logs, errorMsg)); } string dest; switch (bitSize) { case 8: if (!NumberHelper.ParseSignedAsUInt8(intStr, out byte u8)) { return(LogInfo.LogErrorMessage(logs, $"[{intStr}] is not a valid 8bit integer")); } dest = info.Type == MathType.Hex ? $"0x{u8:X2}" : u8.ToString(); break; case 16: if (!NumberHelper.ParseSignedAsUInt16(intStr, out ushort u16)) { return(LogInfo.LogErrorMessage(logs, $"[{intStr}] is not a valid 16bit integer")); } dest = info.Type == MathType.Hex ? $"0x{u16:X4}" : u16.ToString(); break; case 32: if (!NumberHelper.ParseSignedAsUInt32(intStr, out uint u32)) { return(LogInfo.LogErrorMessage(logs, $"[{intStr}] is not a valid 32bit integer")); } dest = info.Type == MathType.Hex ? $"0x{u32:X8}" : u32.ToString(); break; case 64: if (!NumberHelper.ParseSignedAsUInt64(intStr, out ulong u64)) { return(LogInfo.LogErrorMessage(logs, $"[{intStr}] is not a valid 64bit integer")); } dest = info.Type == MathType.Hex ? $"0x{u64:X16}" : u64.ToString(); break; default: throw new InternalException($"Internal Logic Error at Math,{info.Type}"); } List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, dest); logs.AddRange(varLogs); } break; case MathType.Rand: { MathInfo_Rand subInfo = info.SubInfo.Cast <MathInfo_Rand>(); int min = 0; if (subInfo.Min != null) { string minStr = StringEscaper.Preprocess(s, subInfo.Min); if (!NumberHelper.ParseInt32(minStr, out min)) { return(LogInfo.LogErrorMessage(logs, $"[{minStr}] is not a valid integer")); } if (min < 0) { return(LogInfo.LogErrorMessage(logs, $"[{min}] must be positive integer")); } } int max = 65536; if (subInfo.Max != null) { string maxStr = StringEscaper.Preprocess(s, subInfo.Max); if (!NumberHelper.ParseInt32(maxStr, out max)) { return(LogInfo.LogErrorMessage(logs, $"[{maxStr}] is not a valid integer")); } if (max < 0) { return(LogInfo.LogErrorMessage(logs, $"[{max}] must be positive integer")); } if (max <= min) { return(LogInfo.LogErrorMessage(logs, "Maximum bounds must be larger than minimum value")); } } int destInt = s.Random.Next() % (max - min) + min; List <LogInfo> varLogs = Variables.SetVariable(s, subInfo.DestVar, destInt.ToString()); logs.AddRange(varLogs); } break; default: // Error throw new InternalException("Internal Logic Error at CommandMath.Math"); } return(logs); }
public ExpressionOperatorMath(MathType type) { Type = type; }
/// <summary> /// Does either summation or average on weekly, monthly or yearly basis /// </summary> /// <param name="OperationData"></param> /// <param name="sum"></param> private static void TimeAggregation(XElement OperationData, MathType mathtype) { DFS3.MaxEntriesInBuffer = 1; DFS2.MaxEntriesInBuffer = 1; string File1 = OperationData.Element("DFSFileName").Value; DFSBase dfs = DfsFileFactory.OpenFile(File1); int[] Items = ParseString(OperationData.Element("Items").Value, 1, dfs.Items.Count()); string timeinterval = OperationData.Element("TimeInterval").Value.ToLower(); var Tstep = OperationData.Element("TimeIntervalSteps"); int timesteps = 1; if (Tstep != null) { timesteps = int.Parse(Tstep.Value); } string File2; bool samefile = true; if (OperationData.Element("DFSOutputFileName") != null) { File2 = OperationData.Element("DFSOutputFileName").Value; samefile = false; } else { File2 = Path.Combine(Path.GetFileNameWithoutExtension(File1) + "_temp", Path.GetExtension(File1)); } DFSBase outfile = DfsFileFactory.CreateFile(File2, Items.Count()); outfile.CopyFromTemplate(dfs); int k = 0; //Create the items foreach (int j in Items) { int i = j - 1; outfile.Items[k].EumItem = dfs.Items[i].EumItem; outfile.Items[k].EumUnit = dfs.Items[i].EumUnit; outfile.Items[k].Name = dfs.Items[i].Name; k++; } switch (timeinterval) { case "month": outfile.TimeOfFirstTimestep = new DateTime(dfs.TimeOfFirstTimestep.Year, dfs.TimeOfFirstTimestep.Month, 15); outfile.TimeStep = TimeSpan.FromDays(365.0 / 12 * timesteps); dfs.TimeAggregation(Items, outfile, TimeInterval.Month, timesteps, mathtype); break; case "year": outfile.TimeOfFirstTimestep = new DateTime(dfs.TimeOfFirstTimestep.Year, 6, 1); outfile.TimeStep = TimeSpan.FromDays(365.0 * timesteps); dfs.TimeAggregation(Items, outfile, TimeInterval.Year, timesteps, mathtype); break; case "day": outfile.TimeStep = TimeSpan.FromDays(timesteps); dfs.TimeAggregation(Items, outfile, TimeInterval.Day, timesteps, mathtype); break; default: break; } //Close the files dfs.Dispose(); outfile.Dispose(); if (samefile) { File.Delete(File1); FileInfo f = new FileInfo(File2); File.Move(File2, File1); } }