public MatrixValue Function(FunctionValue f, ScalarValue n, ScalarValue dt, ArgumentsValue args) { var numberOfMeasurements = (Int32)n.Value; var timeBetweenMeasurements = (Int32)Math.Floor(dt.Value * 1000); var results = new MatrixValue(numberOfMeasurements, 2); var time = 0.0; for (var i = 1; i <= numberOfMeasurements; i++) { Thread.Sleep(timeBetweenMeasurements); var result = f.Perform(context, args); results[i, 1] = new ScalarValue(time); if (result is ScalarValue) { results[i, 2] = result as ScalarValue; } else if (result is MatrixValue) { var m = result as MatrixValue; for (var j = 1; j <= m.Length; j++) { results[i, 1 + j] = m[j]; } } time += dt.Value; } return results; }
private bool CheckVisibility(TypeValue type, FunctionValue method) { List <TypeValue> methodTypes = new List <TypeValue>(); if (Context.ReadLocalControlVariable(FunctionResolver.calledObjectTypeName).IsDefined(Context)) { foreach (var value in Context.ReadLocalControlVariable(FunctionResolver.calledObjectTypeName).ReadMemory(Context).PossibleValues) { if (value is TypeValue) { methodTypes.Add(value as TypeValue); } } } Name name = method.Name; var visibility = type.Declaration.GetMethodVisibility(name); if (visibility.HasValue) { if (methodTypes.Count() == 0) { if (visibility != Visibility.PUBLIC) { SetWarning("Calling inaccessible method", AnalysisWarningCause.CALLING_INACCESSIBLE_METHOD); return(false); } } else { int numberOfWarings = 0; foreach (var methodType in methodTypes) { if (visibility == Visibility.PRIVATE) { if (!methodType.Declaration.QualifiedName.Equals(type.Declaration.QualifiedName)) { SetWarning("Calling inaccessible method", AnalysisWarningCause.CALLING_INACCESSIBLE_METHOD); numberOfWarings++; } } else if (visibility == Visibility.NOT_ACCESSIBLE) { SetWarning("Calling inaccessible method", AnalysisWarningCause.CALLING_INACCESSIBLE_METHOD); numberOfWarings++; } else if (visibility == Visibility.PROTECTED) { List <QualifiedName> typeHierarchy = new List <QualifiedName>(type.Declaration.BaseClasses); typeHierarchy.Add(type.Declaration.QualifiedName); List <QualifiedName> methodTypeHierarchy = new List <QualifiedName>(methodType.Declaration.BaseClasses); methodTypeHierarchy.Add(methodType.Declaration.QualifiedName); bool isInHierarchy = false; foreach (var className in typeHierarchy) { if (methodTypeHierarchy.Contains(className)) { isInHierarchy = true; break; } } if (isInHierarchy == false) { SetWarning("Calling inaccessible method", AnalysisWarningCause.CALLING_INACCESSIBLE_METHOD); numberOfWarings++; } } } if (numberOfWarings == methodTypes.Count) { return(false); } } } return(true); }
/// <summary> /// Add entry basic block to this function and fill in additional debug info. /// If not called, this is a function declaration. /// </summary> /// <param name="genContext"></param> /// <param name="builder"></param> /// <returns>Entry basic block</returns> public BasicBlock StartDefinition(CodeGeneratorContext genContext, Builder builder) { BasicBlock basicBlock = genContext.Context.AppendBasicBlock(FunctionValue, "entry"); builder.PositionAtEnd(basicBlock); // Build return value storage if necessary Type returnType = FunctionType.ReturnType; if (returnType.Kind != LLVMTypeKind.LLVMVoidTypeKind) { ReturnBlock = genContext.Context.CreateBasicBlock("return"); RetvalStorage = builder.BuildAlloca(returnType, "retval"); } // Visit all declaration nodes and create storage (parameters and variables) StackLayoutGenerator layoutGenerator = new StackLayoutGenerator(new IndexTypeSizeManager()); layoutGenerator.VisitFunctionDefinition(_leaf); FunctionStackLayout layout = layoutGenerator.GetLayout(); foreach (var v in layout.Variables) { Type varType = genContext.LookupType(v.Key.Type) !.Value; Value varStorage = builder.BuildAlloca(varType, v.Key.Name); VariableValues[v.Key] = varStorage; } // Emit store instruction for return value if (RetvalStorage != null && !returnType.IsStructType()) { builder.BuildStore(Value.ConstInt(returnType, 0, true), RetvalStorage.Value); } // Emit store instructions for parameters Value[] funcParams = FunctionValue.Params; for (int i = 0, ilen = funcParams.Length; i < ilen; ++i) { DeclarationNode parameter = _leaf.Parameters[i]; Value paramValue = funcParams[i]; VariableValues.TryGetValue(parameter, out Value varStorage); varStorage.SetName($"{parameter.Name}.addr"); builder.BuildStore(paramValue, varStorage); paramValue.SetName(parameter.Name); } // Create subroutine type debug info genContext.TryGetNodeSymbol(_leaf, out Symbol range); Metadata subroutineType = genContext.DiBuilder.CreateSubroutineType(genContext.DiFile, Array.ConvertAll(_leaf.Parameters, param => genContext.LookupDiType(param.Type) !.Value), LLVMDIFlags.LLVMDIFlagZero); Metadata funcLocation = genContext.Context.CreateDebugLocation(range.LLVMLine, genContext.ColumnInfo ? range.LLVMColumn : 0, DiFwdDecl, Metadata.Null); // Create subroutine debug info and substitute over forward declaration DiFunctionDef = genContext.DiBuilder.CreateFunction(genContext.DiFile, _leaf.Name, _leaf.Name, genContext.DiFile, range.LLVMLine, subroutineType, true, true, range.LLVMLine, LLVMDIFlags.LLVMDIFlagZero, false); DiFwdDecl.ReplaceAllUsesWith(DiFunctionDef); // Create llvm.dbg.declare calls for each parameter's storage if (genContext.DebugInfo) { Metadata paramExpression = genContext.DiBuilder.CreateExpression(); for (int i = 0, ilen = _leaf.Parameters.Length; i < ilen; ++i) { DeclarationNode parameter = _leaf.Parameters[i]; genContext.TryGetNodeSymbol(parameter, out Symbol paramRange); Metadata paramType = genContext.LookupDiType(parameter.Type) !.Value; Metadata paramMetadata = genContext.DiBuilder.CreateParameterVariable(DiFunctionDef, parameter.Name, (uint)i + 1, genContext.DiFile, paramRange.LLVMLine, paramType, true, LLVMDIFlags.LLVMDIFlagZero); VariableValues.TryGetValue(parameter, out Value varStorage); genContext.DiBuilder.InsertDeclareAtEnd(varStorage, paramMetadata, paramExpression, funcLocation, basicBlock); } } // Associate debug info nodes with function FunctionValue.SetFuncSubprogram(DiFunctionDef); return(basicBlock); }
/// <inheritdoc /> public override void VisitFunctionValue(FunctionValue value) { throw new ArgumentException("Expression cannot contain any function value"); }
/// <inheritdoc /> public override void AddFunctiondeclaration(QualifiedName name, FunctionValue declaration) { functionDecl.Add(name, declaration); definitionAdded = true; changeTracker.ModifiedFunction(name); }
public FullCellAddr[] ResidualInputs(FunctionValue fv) { // The residual input cells are those that have input value NA FullCellAddr[] residualInputs = new FullCellAddr[fv.Arity]; int j = 0; for (int i = 0; i < fv.args.Length; i++) if (fv.args[i] == ErrorValue.naError) residualInputs[j++] = inputCells[i]; return residualInputs; }
/// <summary> /// Sets the function. /// </summary> /// <param name="name">The name.</param> /// <param name="declaration">The declaration.</param> internal void SetFunction(QualifiedName name, FunctionValue declaration) { lockedTest(); FunctionDecl.Add(name, declaration); }
public FunctionEntry(Symbol symbol, FunctionValue value) { this.symbol = symbol; this.value = value; }
/// <summary> /// Create a residual (sheet-defined) function for the given FunctionValue. /// As a side effect, register the new SDF and cache it in a dictionary mapping /// function values to residual SDFs. /// </summary> /// <param name="fv">The function value to specialize</param> /// <returns></returns> public static SdfInfo SpecializeAndCompile(FunctionValue fv) { SdfInfo residualSdf; if (!specializations.TryGetValue(fv, out residualSdf)) { FullCellAddr[] residualInputCells = fv.sdfInfo.Program.ResidualInputs(fv); String name = String.Format("{0}#{1}", fv, nextIndex); Console.WriteLine("Created residual function {0}", name); // Register before partial evaluation to enable creation of call cycles residualSdf = Register(fv.sdfInfo.outputCell, residualInputCells, name); specializations.Add(fv, residualSdf); ProgramLines residual = fv.sdfInfo.Program.PEval(fv.args, residualInputCells); residualSdf.Program = residual; Update(residualSdf, residual.CompileToDelegate(residualSdf)); } return residualSdf; }
// BFGF Minimizer public static Value Argmin(Value function, Value initial, Value tolerance, Netlist netlist, Style style, int s) { if (!(initial is ListValue <Value>)) { throw new Error("argmin: expecting a list for second argument"); } Vector <double> initialGuess = CreateVector.Dense((initial as ListValue <Value>).ToDoubleArray("argmin: expecting a list of numbers for second argument")); if (!(tolerance is NumberValue)) { throw new Error("argmin: expecting a number for third argument"); } double toler = (tolerance as NumberValue).value; if (!(function is FunctionValue)) { throw new Error("argmin: expecting a function as first argument"); } FunctionValue closure = function as FunctionValue; if (closure.parameters.parameters.Count != 1) { throw new Error("argmin: initial values and function parameters have different lengths"); } IObjectiveFunction objectiveFunction = ObjectiveFunction.Gradient( (Vector <double> objParameters) => { const string badResult = "argmin: objective function should return a list with a number (cost) and a list of numbers (partial derivatives of cost)"; List <Value> parameters = new List <Value>(); foreach (double parameter in objParameters) { parameters.Add(new NumberValue(parameter)); } ListValue <Value> arg1 = new ListValue <Value>(parameters); List <Value> arguments = new List <Value>(); arguments.Add(arg1); bool autoContinue = netlist.autoContinue; netlist.autoContinue = true; Value result = closure.ApplyReject(arguments, netlist, style, s); if (result == null) { throw new Error(badResult); } netlist.autoContinue = autoContinue; if (!(result is ListValue <Value>)) { throw new Error(badResult); } List <Value> results = (result as ListValue <Value>).elements; if (results.Count != 2 || !(results[0] is NumberValue) || !(results[1] is ListValue <Value>)) { throw new Error(badResult); } double cost = (results[0] as NumberValue).value; ListValue <Value> gradients = results[1] as ListValue <Value>; KGui.gui.GuiOutputAppendText("argmin: parameters=" + arg1.Format(style) + " => cost=" + style.FormatDouble(cost) + ", gradients=" + results[1].Format(style) + Environment.NewLine); return(new Tuple <double, Vector <double> >(cost, CreateVector.Dense(gradients.ToDoubleArray(badResult)))); }); try { BfgsMinimizer minimizer = new BfgsMinimizer(toler, toler, toler); MinimizationResult result = minimizer.FindMinimum(objectiveFunction, initialGuess); if (result.ReasonForExit == ExitCondition.Converged || result.ReasonForExit == ExitCondition.AbsoluteGradient || result.ReasonForExit == ExitCondition.RelativeGradient) { List <Value> elements = new List <Value>(); for (int i = 0; i < result.MinimizingPoint.Count; i++) { elements.Add(new NumberValue(result.MinimizingPoint[i])); } ListValue <Value> list = new ListValue <Value>(elements); KGui.gui.GuiOutputAppendText("argmin: converged with parameters " + list.Format(style) + " and reason '" + result.ReasonForExit + "'" + Environment.NewLine); return(list); } else { throw new Error("reason '" + result.ReasonForExit.ToString() + "'"); } } catch (Exception e) { throw new Error("argmin ended: " + ((e.InnerException == null) ? e.Message : e.InnerException.Message)); } // somehow we need to recatch the inner exception coming from CostAndGradient }
/// <inheritdoc /> public abstract void AddFunctiondeclaration(QualifiedName name, FunctionValue declaration);
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public void update() throws org.maltparser.core.exception.MaltChainedException public void update() { multipleFeatureValue.reset(); parentFeature.update(); FunctionValue value = parentFeature.FeatureValue; if (value is SingleFeatureValue) { string symbol = ((SingleFeatureValue)value).Symbol; if (((FeatureValue)value).NullValue) { multipleFeatureValue.addFeatureValue(parentFeature.SymbolTable.getSymbolStringToCode(symbol), symbol); multipleFeatureValue.NullValue = true; } else { string[] items; try { items = separatorsPattern.split(symbol); } catch (PatternSyntaxException e) { throw new FeatureException("The split feature '" + ToString() + "' could not split the value using the following separators '" + separators + "'", e); } for (int i = 0; i < items.Length; i++) { if (items[i].Length > 0) { multipleFeatureValue.addFeatureValue(table.addSymbol(items[i]), items[i]); } } multipleFeatureValue.NullValue = false; } } else if (value is MultipleFeatureValue) { if (((MultipleFeatureValue)value).NullValue) { multipleFeatureValue.addFeatureValue(parentFeature.SymbolTable.getSymbolStringToCode(((MultipleFeatureValue)value).FirstSymbol), ((MultipleFeatureValue)value).FirstSymbol); multipleFeatureValue.NullValue = true; } else { foreach (string symbol in ((MultipleFeatureValue)value).Symbols) { string[] items; try { items = separatorsPattern.split(symbol); } catch (PatternSyntaxException e) { throw new FeatureException("The split feature '" + ToString() + "' could not split the value using the following separators '" + separators + "'", e); } for (int i = 0; i < items.Length; i++) { multipleFeatureValue.addFeatureValue(table.addSymbol(items[i]), items[i]); } multipleFeatureValue.NullValue = false; } } } }