public void VerifyPropertiesOfVariableOfTypeShort() { Type declaredType = typeof(short); Variable<short> vInt = new Variable<short>(Guid.Empty); Assert.Equal(declaredType, vInt.DataType); }
void Initialize() { foreach (var variable in locals) variableToValue[variable] = new Variable(); foreach (var block in allBlocks) { for (int i = 0; i < block.Instructions.Count; i++) { var instr = block.Instructions[i]; switch (instr.OpCode.Code) { case Code.Stloc: case Code.Stloc_S: case Code.Stloc_0: case Code.Stloc_1: case Code.Stloc_2: case Code.Stloc_3: var variable = Instr.GetLocalVar(locals, instr); var val = variableToValue[variable]; val.AddWrite(); object obj; if (!GetValue(block, i, out obj)) val.SetUnknown(); val.Value = obj; break; default: break; } } } }
internal static object DCArg(Variable v) { P6any o = v.Fetch(); var s = o.mo.setting; if (o is BoxObject<object>) return Kernel.UnboxAny<object>(o); else if (o.IsDefined()) { if (o.Isa(s.StrMO)) return (string) o.mo.mro_raw_Str.Get(v); else if (o.Isa(s.BoolMO)) return (bool) o.mo.mro_raw_Bool.Get(v); else if (o.Isa(s.NumMO)) { double d = Kernel.UnboxAny<double>(o); if ((d % 1) == 0 && d <= int.MaxValue && d >= int.MinValue) return (object)(int)d; return (object)d; } else if (o.Isa(s.ListMO)) { VarDeque it = o.mo.mro_raw_iterator.Get(v); var lo = new List<object>(); while (Kernel.IterHasFlat(it, true)) lo.Add(DCArg(it.Shift())); return lo.ToArray(); } else return (int) o.mo.mro_raw_Numeric.Get(v); } else return null; }
public void VerifyPropertiesOfVariableOfTypeBool() { Type declaredType = typeof(bool); Variable<bool> vInt = new Variable<bool>(Guid.Empty); Assert.Equal(declaredType, vInt.DataType); }
public void VerifyPropertiesOfVariableOfTypeGuid() { Type declaredType = typeof(Guid); Variable<Guid> vInt = new Variable<Guid>(Guid.Empty); Assert.Equal(declaredType, vInt.DataType); }
public Procedure(string name, VariableSequence valArgs, Variable resultArg, StatementSequence statements) { AddChild(valArgs); AddChild(resultArg); AddChild(statements); _name = name; }
/// <summary> /// Initializes a new instance of the <see cref="WrongCodeTypeException" /> class. /// </summary> /// <param name="variable">The variable.</param> /// <param name="argumentName">Name of the argument.</param> /// <param name="expectedText">The expected text.</param> public WrongCodeTypeException(Variable variable, string argumentName, string expectedText) : base(string.Format("Wrong code type [{0}] of passed parameter '{1}'. Expected {2}.", variable.GetCodeType().Name, argumentName, expectedText)) { Variable = variable; CodeType = variable.GetCodeType(); ArgumentName = argumentName; }
public LinkVariableAction(VariableInfo variableInfo, Variable linkedVariable) { VariableInfo = variableInfo; OldLink = variableInfo.Variable.Linked; OldValue = variableInfo.Value; NewLink = linkedVariable; }
public SentimentIndex() : base("Sentiment Index") { numberOfTrainingItems = Variable.New<int>(); var rangeOfTrainingItems = new Range(numberOfTrainingItems); trainingInputs = Variable.Array<Vector>(rangeOfTrainingItems); trainingOutputs = Variable.Array<bool>(rangeOfTrainingItems); weights = Variable.Random(new VectorGaussian(Vector.Zero(numberOfFeatures), PositiveDefiniteMatrix.Identity(numberOfFeatures))); using (Variable.ForEach(rangeOfTrainingItems)) { trainingOutputs[rangeOfTrainingItems] = Variable.IsPositive(Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(weights, trainingInputs[rangeOfTrainingItems]), noise)); } trainingEngine = new InferenceEngine(); trainingEngine.ShowProgress = false; numberOfTestingItems = Variable.New<int>(); var rangeOfTestingItems = new Range(numberOfTestingItems); testingInputs = Variable.Array<Vector>(rangeOfTestingItems); testingOutputs = Variable.Array<bool>(rangeOfTestingItems); weightsPosteriorDistribution = Variable.New<VectorGaussian>(); var testWeights = Variable<Vector>.Random(weightsPosteriorDistribution); using (Variable.ForEach(rangeOfTestingItems)) { testingOutputs[rangeOfTestingItems] = Variable.IsPositive(Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(testWeights, testingInputs[rangeOfTestingItems]), noise)); } testingEngine = new InferenceEngine(); testingEngine.ShowProgress = false; }
public void Test_Double_Variable_Value_Set() { Variable<double> testVar = new Variable<double>("testVar", default(double), false); testVar.SetValue(11.15623); double value = testVar.Value; Assert.AreEqual(11.15623, value, "Value setter does not work properly.<Double>"); }
public void SeriesChangesWhenFunctionBindingListChanges() { IFunction function = new Function(); IVariable yVariable = new Variable<double>("y"); IVariable xVariable = new Variable<double>("x"); function.Arguments.Add(xVariable); function.Components.Add(yVariable); function[1.0] = 2.0; function[2.0] = 5.0; function[3.0] = 1.0; ILineChartSeries ls = ChartSeriesFactory.CreateLineSeries(); ls.YValuesDataMember = function.Components[0].DisplayName; ls.XValuesDataMember = function.Arguments[0].DisplayName; var synchronizeObject = new Control(); synchronizeObject.Show(); var functionBindingList = new FunctionBindingList(function) { SynchronizeInvoke = synchronizeObject }; ls.DataSource = functionBindingList; //a change in the function should change the series function[1.0] = 20.0; while(functionBindingList.IsProcessing) { Application.DoEvents(); } Assert.AreEqual(20, ls.YValues[0]); }
private void HandleFailure(Variable failure) { var defaultPair = DefaultPrivacyProvider.DefaultPair; var time = Group.EngineTimeData; Response = new ReportMessage( Request.Version, new Header( new Integer32(Request.MessageId()), new Integer32(Messenger.MaxMessageSize), 0), // no need to encrypt. new SecurityParameters( Group.EngineId, new Integer32(time[0]), new Integer32(time[1]), Request.Parameters.UserName, defaultPair.AuthenticationProvider.CleanDigest, defaultPair.Salt), new Scope( Group.EngineId, OctetString.Empty, new ReportPdu( Request.RequestId(), ErrorCode.NoError, 0, new List<Variable>(1) { failure })), defaultPair, null); if (TooBig) { GenerateTooBig(); } }
public void SetDateTime() { IVariable<DateTime> var = new Variable<DateTime>(); DateTime to = DateTime.Now; var.Values.Add(to); Assert.IsTrue(var.Values.Contains(to)); }
public void Test(string testDll, Variable<int> performed, Variable<int> total) { bool success = false; try { success = MakeTestFromCommandLine(_testDomain, testDll); } catch(System.IO.FileNotFoundException) { new Message("Failed opening " + testDll); return; } if (!success) { Console.Error.WriteLine("Unable to locate fixture"); return; } total.Value = _testRunner.CountTestCases(TestFilter.Empty); var collector = new EventCollector(Console.Out, Console.Error, performed); var result = _testRunner.Run(collector); }
public static double Integral(string Expression, double LowerIndex, double UpperIndex, char IterationVariable, int Kind) { var parser = new MathParser(); var Var = new Variable<double>(IterationVariable.ToString()); parser.Variables.Add(Var); parser.Parse(Expression); Func<double,double> proc = x => { Var.Value = x; return parser.Evaluate(); }; switch (Kind) { case 0: return Integration.Trapezoidal(LowerIndex, UpperIndex, proc); case 1: return Integration.LeftHand(LowerIndex, UpperIndex, proc); default: return Integration.MidPoint(LowerIndex, UpperIndex, proc); } }
protected override void InitializeCulture() { string lang = "en"; if ( Context.Request.QueryString["lang"] != null ) { lang = Context.Request.QueryString["lang"]; switch ( lang ) { case "cz": case "cs": Thread.CurrentThread.CurrentCulture = new CultureInfo("cs-CZ"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("cs-CZ"); break; default: Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); break; } } else { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } // this code is invoked, when the form is posted back. // (after pressing the "OK" button) // The page is then redirected to a different URL if ( Context.Request.Form.Count > 0 ) { Variable varInfo = new Variable(4); string ctlHeading = @"ctl00$cph_main$"; string varName = Context.Request.Form[ctlHeading + "listbox_variable"]; string stName = Context.Request.Form[ctlHeading + "txt_station"]; //string periodStr = Context.Request.Form[ctlHeading + "listbox_period"]; string yearStr = Context.Request.Form[ctlHeading + "listbox_year"]; string monthStr = Context.Request.Form[ctlHeading + "listbox_month"]; string dayStr = Context.Request.Form[ctlHeading + "listbox_day"]; string yearStr2 = Context.Request.Form[ctlHeading + "listbox_year2"]; string monthStr2 = Context.Request.Form[ctlHeading + "listbox_month2"]; string dayStr2 = Context.Request.Form[ctlHeading + "listbox_day2"]; string varUrl = ProcessVariable(varName, varInfo); string stUrl = ProcessStation(stName, varInfo); //string dateUrl = ProcessDate(yearStr, monthStr, dayStr); string periodUrl = ProcessPeriod(yearStr, monthStr, dayStr, yearStr2, monthStr2, dayStr2); // generate url of the new page! string newUrl = String.Format(@"~/{0}/{1}/{2}/{3}.aspx", lang, varUrl, stUrl, periodUrl); // redirect the browser to the new page! Context.Response.Redirect(newUrl); } }
public Variable CreateFLV(string name) { if (name == null) throw new ArgumentNullException("name"); if (_variables.ContainsKey(name)) throw new Exception(); return _variables[name] = new Variable(); }
public void GetArgumentDependentVariables() { IFunction f = new Function(); IVariable c1 = new Variable<int>("c1"); IVariable c2 = new Variable<int>("c2"); IVariable x = new Variable<int>("x"); f.Components.Add(c1); f.Components.Add(c2); IDictionary<IVariable, IEnumerable<IVariable>> dependentVariables = MemoryFunctionStoreHelper.GetDependentVariables(f.Store.Functions); //no argument dependencies yet Assert.AreEqual(2, dependentVariables.Count); Assert.AreEqual(new IVariable[0],dependentVariables[c1].ToArray()); Assert.AreEqual(new IVariable[0], dependentVariables[c2].ToArray()); f.Arguments.Add(x); dependentVariables = MemoryFunctionStoreHelper.GetDependentVariables(f.Store.Functions); Assert.AreEqual(3, dependentVariables.Count); Assert.AreEqual(2, dependentVariables[x].Count()); Assert.AreEqual(new[]{c1,c2},dependentVariables[x]); //Assert.IsTrue(dependentVariables[x].Contains(c1)); }
public ArrayAssignment(int lineNumber, Variable array, Variable index, Variable value) : base(lineNumber) { this.array = array; this.index = index; this.value = value; }
/// <summary> /// Visits the call. /// </summary> /// <param name="destination">The destination.</param> /// <param name="receiver">The receiver.</param> /// <param name="callee">The callee.</param> /// <param name="arguments">The arguments.</param> /// <param name="isVirtualCall">if set to <c>true</c> [is virtual call].</param> /// <param name="programContext">The program context.</param> /// <param name="stateBeforeInstruction">The state before instruction.</param> /// <param name="stateAfterInstruction">The state after instruction.</param> public override void VisitCall( Variable destination, Variable receiver, Method callee, ExpressionList arguments, bool isVirtualCall, Microsoft.Fugue.IProgramContext programContext, Microsoft.Fugue.IExecutionState stateBeforeInstruction, Microsoft.Fugue.IExecutionState stateAfterInstruction) { if ((callee.DeclaringType.GetRuntimeType() == typeof(X509ServiceCertificateAuthentication) || callee.DeclaringType.GetRuntimeType() == typeof(X509ClientCertificateAuthentication)) && (callee.Name.Name.Equals("set_CertificateValidationMode", StringComparison.InvariantCultureIgnoreCase))) { IAbstractValue value = stateBeforeInstruction.Lookup((Variable)arguments[0]); IIntValue intValue = value.IntValue(stateBeforeInstruction); if (intValue != null) { X509CertificateValidationMode mode = (X509CertificateValidationMode)intValue.Value; if (mode != X509CertificateValidationMode.ChainTrust) { Resolution resolution = base.GetResolution(mode.ToString(), X509CertificateValidationMode.ChainTrust.ToString()); Problem problem = new Problem(resolution, programContext); base.Problems.Add(problem); } } } base.VisitCall(destination, receiver, callee, arguments, isVirtualCall, programContext, stateBeforeInstruction, stateAfterInstruction); }
public override void Train() { InitModel(); // define variables var avg = Ratings.Average; var ub = new Variable(); var ib = new Variable(); var r = new Variable(); // define function to minimize var func = TermBuilder.Power(avg + ub + ib - r, 2); var func_compiled = func_min.Compile(); double learn_rate = 0.0001; for (int i = 0; i < NumIter; i++) foreach (int j in Ratings.RandomIndex) { // get data var data = new double[] { user_bias[Ratings.Users[j]], item_bias[Ratings.Items[j]], Ratings[j] }; // compute gradient var gradient = func_compiled.Differentiate(data); // update user_bias[Ratings.Users[j]] -= learn_rate * gradient[0]; item_bias[Ratings.Items[j]] -= learn_rate * gradient[1]; } }
public void ConvertOneArgumentOfTwoDimensionalFunction() { IFunction func = new Function(); IVariable<int> x = new Variable<int>("x"); IVariable<DateTime> t = new Variable<DateTime>("t"); var fx = new Variable<int>(); func.Arguments.Add(x); func.Arguments.Add(t); func.Components.Add(fx); DateTime t0 = DateTime.Now; func[10,t0] = 4; IFunction convertedFunction = new ConvertedFunction<string, int>(func, x, Convert.ToInt32, Convert.ToString); //notice both argument and component are converted Assert.IsTrue(convertedFunction.Arguments[0] is IVariable<string>); Assert.IsTrue(convertedFunction.Components[0] is IVariable<int>); //notice the argument has been converted to a string variable Assert.AreEqual(4, convertedFunction["10",t0]); Assert.AreEqual(4, convertedFunction.Components[0].Values[0,0]); //arguments of components are converted as well :) Assert.AreEqual(4, convertedFunction.Components[0]["10",t0]); convertedFunction["30",t0] = 10; IMultiDimensionalArray<string> strings = (IMultiDimensionalArray<string>)convertedFunction.Arguments[0].Values; Assert.IsTrue(new[] { "10", "30" }.SequenceEqual(strings)); }
public void TestAsArgument() { IVariable<IFeatureLocation> a = new Variable<IFeatureLocation>("argument"); IVariable<double> c1 = new Variable<double>("value"); IVariable<string> c2 = new Variable<string>("description"); // f = (a, p)(h) IFunction f = new Function("rating curve"); f.Arguments.Add(a); f.Components.Add(c1); f.Components.Add(c2); SimpleFeature simpleFeature = new SimpleFeature(10.0); IFeatureLocation featureLocation = new FeatureLocation { Feature = simpleFeature }; // value based argument referencing. f[featureLocation] = new object[] { 1.0, "jemig de pemig" }; IMultiDimensionalArray<double> c1Value = f.GetValues<double>(new ComponentFilter(f.Components[0]), new VariableValueFilter<IFeatureLocation>( f.Arguments[0], new FeatureLocation {Feature = simpleFeature})); Assert.AreEqual(1.0, c1Value[0], 1.0e-6); //IMultiDimensionalArray<string> c2Value = f.GetValues<string>(new ComponentFilter(f.Components[1]), // new VariableValueFilter<IFeatureLocation>( // f.Arguments[0], featureLocation)); //Assert.AreEqual("jemig de pemig", c2Value[0]); }
public override bool TryGetMember(GetMemberBinder binder, out object result) { try { Variable variable; if(!variables.TryGetValue(binder.Name, out variable)) { int idx = GetGlobalVarIndexByName(binder.Name); var ptr = GetAddressOfGlobalVar(idx); if(ptr == IntPtr.Zero) { result = null; return true; } int tid; GetGlobalVar(idx, out tid); var instance = ScriptEngine.GetVariable(ptr, tid); variables[binder.Name] = variable = new Variable(instance, ptr, tid); } result = ScriptEngine.GetVariable(variable.Address, variable.TypeId, variable.Instance); return true; } catch(Exception ex) { ScriptEngine.Log ("Exception caught while fetching '{0}' variable of module '{1}': {2}.", binder.Name, Name, ex.Message); result = null; return false; } }
private double UpdateHelper(Message<GaussianDistribution> message1, Message<GaussianDistribution> message2, Variable<GaussianDistribution> variable1, Variable<GaussianDistribution> variable2) { GaussianDistribution message1Value = message1.Value.Clone(); GaussianDistribution message2Value = message2.Value.Clone(); GaussianDistribution marginal1 = variable1.Value.Clone(); GaussianDistribution marginal2 = variable2.Value.Clone(); double a = _Precision/(_Precision + marginal2.Precision - message2Value.Precision); GaussianDistribution newMessage = GaussianDistribution.FromPrecisionMean( a*(marginal2.PrecisionMean - message2Value.PrecisionMean), a*(marginal2.Precision - message2Value.Precision)); GaussianDistribution oldMarginalWithoutMessage = marginal1/message1Value; GaussianDistribution newMarginal = oldMarginalWithoutMessage*newMessage; /// Update the message and marginal message1.Value = newMessage; variable1.Value = newMarginal; /// Return the difference in the new marginal return newMarginal - marginal1; }
/// <summary> /// Compute score for vectors, and constrain the score require to be the maximum /// for the class inferred in model results /// </summary> protected void ComputeAndConstrainScores(Variable<Vector>[] variableVector) { using (Variable.ForEach(this.range)) { var score = new Variable<double>[numOfClasses]; var scorePlusNoise = new Variable<double>[numOfClasses]; for (int i = 0; i < numOfClasses; i++) { score[i] = Variable.InnerProduct(variableVector[i], this.featureVectors[this.range]); scorePlusNoise[i] = Variable.GaussianFromMeanAndPrecision(score[i], Noise); } this.modelOutput[this.range] = Variable.DiscreteUniform(numOfClasses); for (int j = 0; j < numOfClasses; j++) { using (Variable.Case(this.modelOutput[this.range], j)) { for (int k = 0; k < scorePlusNoise.Length; k++) { if (k != j) { Variable.ConstrainPositive(scorePlusNoise[j] - scorePlusNoise[k]); } } } } } }
public Window1() { InitializeComponent(); //------------------------ // The model //------------------------ // c represents the position of the car c = Variable.DiscreteUniform(3).Named("Car"); // p represents the pick. This will be observed p = Variable.DiscreteUniform(3).Named("Pick"); // h represents the host pick. h = Variable.New<int>().Named("Host"); // Whether the host is observed hostIsObserved = Variable.Observed<bool>(false); for (int a = 0; a < 3; a++) for (int b = 0; b < 3; b++) { double[] probs = { 1, 1, 1 }; for (int ps = 0; ps < 3; ps++) if (ps == a || ps == b) probs[ps] = 0; using (Variable.Case(p, a)) using (Variable.Case(c, b)) h.SetTo(Variable.Discrete(probs)); } using (Variable.If(hostIsObserved)) Variable.ConstrainFalse(h == c); // Compile the model getProbs(h); OnReset(); }
/// <summary> /// Добавляет переменную в окружение /// </summary> /// <param name="var">Переменная</param> /// <param name="name">Имя переменной</param> public void Add(Variable var, string name) { EnvironsStuct es = new EnvironsStuct(); es.name = name; es.value = var; enviroment.Add(es); }
public void Clone() { var x = new Variable<int>("x") { Values = {1, 2, 3}, Unit = new Unit("distance", "m"), ExtrapolationType = ExtrapolationType.Constant, InterpolationType = InterpolationType.Linear }; var clone = (IVariable<int>)x.Clone(); //Assert.IsTrue(clone.Values.SequenceEqual(new[] {1, 2, 3})); Assert.AreEqual(x.Name, clone.Name); Assert.AreNotEqual(x, clone); Assert.AreNotEqual(x.Store, clone.Store); // clone creates a new deep copy of the variable (in-memory) x.Values .Should("values must be copied").Have.SameSequenceAs(new[] { 1, 2, 3 }); Assert.AreEqual(x.ExtrapolationType, clone.ExtrapolationType); Assert.AreEqual(x.InterpolationType, clone.InterpolationType); Assert.AreNotSame(x.Unit, clone.Unit); Assert.AreEqual(x.Unit.Name, clone.Unit.Name); Assert.AreEqual(x.Unit.Symbol, clone.Unit.Symbol); }
protected override IEnumerable <Variable> resolveVariables(IGenerationModel chain) { _store = chain.FindVariable(typeof(IFakeStore)); yield return(_store); }
public override Implementation VisitImplementation(Implementation node) { if (civlTypeChecker.procToAtomicAction.ContainsKey(node.Proc) || civlTypeChecker.procToIntroductionAction.ContainsKey(node.Proc) || civlTypeChecker.procToLemmaProc.ContainsKey(node.Proc)) return node; node.PruneUnreachableBlocks(); node.ComputePredecessorsForBlocks(); GraphUtil.Graph<Block> graph = Program.GraphFromImpl(node); graph.ComputeLoops(); HashSet<Variable> start = new HashSet<Variable>(globalVarToDomainName.Keys); for (int i = 0; i < node.InParams.Count; i++) { Variable v = node.Proc.InParams[i]; string domainName = FindDomainName(v); if (domainName != null) { var kind = FindLinearKind(v); inParamToLinearQualifier[node.InParams[i]] = new LinearQualifier(domainName, kind); if (kind == LinearKind.LINEAR || kind == LinearKind.LINEAR_IN) { start.Add(node.InParams[i]); } } } for (int i = 0; i < node.OutParams.Count; i++) { string domainName = FindDomainName(node.Proc.OutParams[i]); if (domainName != null) { outParamToDomainName[node.OutParams[i]] = domainName; } } var oldErrorCount = checkingContext.ErrorCount; var impl = base.VisitImplementation(node); if (oldErrorCount < checkingContext.ErrorCount) return impl; Stack<Block> dfsStack = new Stack<Block>(); HashSet<Block> dfsStackAsSet = new HashSet<Block>(); availableLinearVars[node.Blocks[0]] = start; dfsStack.Push(node.Blocks[0]); dfsStackAsSet.Add(node.Blocks[0]); while (dfsStack.Count > 0) { Block b = dfsStack.Pop(); dfsStackAsSet.Remove(b); HashSet<Variable> end = PropagateAvailableLinearVarsAcrossBlock(b); if (b.TransferCmd is ReturnCmd) { foreach (GlobalVariable g in globalVarToDomainName.Keys.Except(end)) { Error(b.TransferCmd, $"Global variable {g.Name} must be available at a return"); } foreach (Variable v in node.InParams) { if (FindDomainName(v) == null || FindLinearKind(v) == LinearKind.LINEAR_IN || end.Contains(v)) continue; Error(b.TransferCmd, $"Input variable {v.Name} must be available at a return"); } foreach (Variable v in node.OutParams) { if (FindDomainName(v) == null || end.Contains(v)) continue; Error(b.TransferCmd, $"Output variable {v.Name} must be available at a return"); } continue; } GotoCmd gotoCmd = b.TransferCmd as GotoCmd; foreach (Block target in gotoCmd.labelTargets) { if (!availableLinearVars.ContainsKey(target)) { availableLinearVars[target] = new HashSet<Variable>(end); dfsStack.Push(target); dfsStackAsSet.Add(target); } else { var savedAvailableVars = new HashSet<Variable>(availableLinearVars[target]); availableLinearVars[target].IntersectWith(end); if (savedAvailableVars.IsProperSupersetOf(availableLinearVars[target]) && !dfsStackAsSet.Contains(target)) { dfsStack.Push(target); dfsStackAsSet.Add(target); } } } } if (graph.Reducible) { foreach (Block header in graph.Headers) { foreach (GlobalVariable g in globalVarToDomainName.Keys.Except(availableLinearVars[header])) { Error(header, $"Global variable {g.Name} must be available at a loop head"); } } } return impl; }
public SqlTransactionFrame() { Transaction = new Variable(typeof(SqlTransaction), this); }
public static Constraint GetConstraint() { List <Type> allowedTypes = new List <Type> { typeof(Sequence), typeof(WriteLine), typeof(Assign) }; Variable <String> buffer = new Variable <String>("buffer", String.Empty); Variable <Boolean> result = new Variable <Boolean>("result", false); DelegateInArgument <MySequenceWithConstraint> element = new DelegateInArgument <MySequenceWithConstraint>(); DelegateInArgument <ValidationContext> vc = new DelegateInArgument <ValidationContext>(); DelegateInArgument <Activity> child = new DelegateInArgument <Activity>(); return(new Constraint <MySequenceWithConstraint> { Body = new ActivityAction <MySequenceWithConstraint, ValidationContext> { Argument1 = element, Argument2 = vc, Handler = new Sequence { Variables = { result, buffer }, Activities = { new ForEach <Activity> { Values = new GetChildSubtree { ValidationContext = vc }, Body = new ActivityAction <Activity> { Argument = child, Handler = new If() { Condition = new InArgument <Boolean>(ac => allowedTypes.Contains( child.Get(ac).GetType())), Else = new Assign <String> { To = buffer, Value = new InArgument <String>(ac => child.Get(ac).GetType().ToString()) } } } }, new AssertValidation { Assertion = new InArgument <Boolean>(result), Message = new InArgument <String>(buffer), PropertyName = new InArgument <String>( (env) => element.Get(env).DisplayName) } } } } }); }
public Bound(Variable var) { itsVariable = var; }
public IEnumerator Execute(StormExecutor executor, Variable variable) { yield return(new WaitForSeconds(time)); }
private LocalVariable OldGlobalLocal(Variable v) { return(new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, $"civl_global_old_{v.Name}", v.TypedIdent.Type))); }
/* * Function executes a single line in the current script after it has already been processed into an array of arguments * Parameter afterSave controls whether the line is the first line after loading a saved game, in which case it does not execute text lines (as the text is contained in the save) */ private void ExecuteCommand(List <String> command, bool afterSave) { int intValue; bool boolValue; // Runs function corresponding to the command with the variables given switch (command[0]) { // Setup case "label": if (command.Count == 3) { _assets.CreateLabel(command[2], currentScriptIndex.ToString(), command[1]); } break; case "image": switch (command.Count) { case 3: _assets.CreateBackground(command[1], command[2], true); break; case 4: _assets.AddImageToCharacter(command[1], command[2], command[3]); break; } break; case "character": if (command.Count == 4) { if (command.Contains("abbreviation")) { _assets.AddAbbreviationToCharacter(command[1], command[3]); break; } if (command.Contains("height")) { _assets.SetCharacterHeight(command[1], command[3]); break; } if (command.Contains("horizontalOffset")) { _assets.SetCharacterOffset(command[1], command[3], false); break; } if (command.Contains("verticalOffset")) { _assets.SetCharacterOffset(command[1], command[3], true); break; } } switch (command.Count) { case 4: _assets.CreateCharacter(command[1], command[2], command[3]); break; case 3: _assets.CreateCharacter(command[1], command[2]); break; case 2: _assets.CreateCharacter(command[1]); break; } break; case "color": if (command.Count == 5) { _assets.SetCharacterColor(command[1], command[2], command[3], command[4]); } break; case "sound": if (command.Count == 3) { _assets.CreateSound(command[1], command[2], false); } break; case "music": if (command.Count == 3) { _assets.CreateSound(command[1], command[2], true); } break; case "video": if (command.Count == 3) { _assets.CreateVideo(command[1], command[2]); } break; case "choice": if (command.Count == 3 && command[1] == "create") { _assets.CreateChoice(command[2]); } else if (command.Count == 5) { string choiceName = command[1]; if (command[2] == "set" && command[3] == "text") { _assets.EditChoiceText(choiceName, command[4]); } else if (command[2] == "add") { _assets.AddOptionToChoice(choiceName, command[3], command[4]); } } break; case "font": if (command.Count == 3) { SetFont(command[1], command[2]); } break; // Script navigation case "jump": if (command.Count == 2) { JumpToLabel(command[1]); } break; case "include": if (command.Count == 2) { _scripts.Add(new Script(command[1], _scripts.Count)); ProcessScript(_scripts.Count - 1); } break; case "comment": break; // Graphics case "show": // Additional options if (command.Contains("pause")) { Settings.executeNext = false; } int fadeDuration = 0; if (command.Contains("fade")) { int commandIndex = command.FindIndex(s => s == "fade"); int.TryParse(command[commandIndex + 1], out fadeDuration); } if (command.Count >= 2) { // Try to show background with given name if (ShowBackground(command[1], fadeDuration)) { break; } // Try to show choice with given name if (ShowChoice(command[1])) { Settings.executeNext = false; break; } } // Try to show character with given name if (command.Count >= 4) { if (command.Contains("left")) { if (ShowCharacter(command[1], command[2], fadeDuration, "left")) { break; } } if (command.Contains("right")) { if (ShowCharacter(command[1], command[2], fadeDuration, "right")) { break; } } else { if (ShowCharacter(command[1], command[2], fadeDuration)) { break; } } } break; case "clear": int unprocessedParts = command.Count - 1; if (command.Contains("pause")) { unprocessedParts--; Settings.executeNext = false; } fadeDuration = 0; if (command.Contains("fade")) { unprocessedParts--; int commandIndex = command.FindIndex(s => s == "fade"); if (int.TryParse(command[commandIndex + 1], out fadeDuration)) { unprocessedParts--; } } if (command.Contains("background")) { ClearBackground(fadeDuration); break; } if (unprocessedParts > 0) { ClearCharacters(fadeDuration, command[1]); break; } ClearCharacters(fadeDuration); break; case "ui": if (command.Contains("pause")) { Settings.executeNext = false; } if (command.Contains("show")) { ManipulateUI(true); } else if (command.Contains("hide")) { ManipulateUI(false); } break; // Sound and video case "play": if (command.Contains("pause")) { Settings.executeNext = false; } bool allowProgress = command.Contains("progress"); bool hideUI = command.Contains("hide"); bool repeat = command.Contains("repeat") || command.Contains("r"); double volume = 1.0; if (command.Count >= 3) { double.TryParse(command[2], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out volume); } if (PlaySound(command[1], volume, repeat)) { break; } PlayVideo(command[1], volume, allowProgress, hideUI); break; case "stop": if (command.Contains("pause")) { Settings.executeNext = false; } switch (command[1]) { case "sound": StopSound(true); break; case "music": StopMusic(true); break; case "video": StopVideo(); break; default: StopSound(true); StopMusic(true); StopVideo(); break; } break; case "save": SaveGame(0); break; case "end": Settings.executeNext = false; EndGame(); break; // Variable manipulation case "int": if (Int32.TryParse(command[2], out intValue)) { _assets.CreateVariable(command[1], intValue); } break; case "bool": if (Boolean.TryParse(command[2], out boolValue)) { _assets.CreateVariable(command[1], boolValue); } break; case "if": Variable var = _assets.variables.Find(i => i.name == command[1]); if (var == null) { break; } switch (var) { case Assets.Boolean boolVal: if (Boolean.TryParse(command[3], out boolValue)) { if (boolValue == boolVal.value) { JumpToLabel(command[4]); } } break; case Integer intVal: if (Int32.TryParse(command[3], out intValue)) { switch (command[2]) { case "<" when intVal.value <intValue: case ">" when intVal.value> intValue: case "=" when intVal.value == intValue: JumpToLabel(command[4]); break; } } break; } break; case "add": if (Int32.TryParse(command[2], out intValue)) { _assets.IntegerAdd(command[1], intValue); } break; case "subtract": if (Int32.TryParse(command[2], out intValue)) { _assets.IntegerSubtract(command[1], intValue); } break; case "set": if (Int32.TryParse(command[2], out intValue)) { _assets.IntegerSet(command[1], intValue); } else if (Boolean.TryParse(command[2], out boolValue)) { _assets.BooleanSet(command[1], boolValue); } break; // Settings case "name": if (command.Count == 3) { if (command[1] == "game") { Settings.gameName = command[2]; this.Title = command[2]; } else if (command[1] == "protagonist") { Settings.protagonistName = command[2]; } } break; // Text default: if (!afterSave) { if (!ExecuteTextCommand(command)) { MessageBox.Show("Error in displaying text on line " + _scripts[currentScriptIndex].currentLine + "!"); } Settings.executeNext = false; } break; } }
///<summary> ///Esta función recibe un Biotipo (lugar). Consulta la ontología por las variables que miden el biotipo y posteriormente ///consulta el indice por cada variable con el fin de seleccionar los posibles sensores que pueden medir dicha información ///y asi poder desplegarla en un servicio de aplicación. ///</summary> ///<returns> ///Biotipo con la información medioambiental. /// </returns> /// <param name="nodoBiotipo">Es el biotipo que ha sido identificado y se desea su información</param> /// <param name="radio">Radio que define el área de acción del Biotipo</param> /// <param name="idioma">Idioma de preferencia del usuario. Por defecto busca Español</param> public Biotipo ObtenerInfoBiotipoMedioAmbiente(GeonameNode nodoBiotipo, string radio, string idioma) { //Objeto del negocio ServiciosMedioAmbientales sm = new ServiciosMedioAmbientales(); //Biotipo generado para presentarlo al usuario Biotipo bio = new Biotipo(); /****************** Obtenemos los Datos Generales del Biotipo **********************/ bio.GeonameId = nodoBiotipo.geonameId; bio.name = nodoBiotipo.Nombre_lugar; bio.CountryName = nodoBiotipo.Nombre_pais; bio.CountryCode = nodoBiotipo.Codigo_pais; bio.AreaImpacto.lat = nodoBiotipo.Latitud; bio.AreaImpacto.lon = nodoBiotipo.Longitud.ToString(); bio.AreaImpacto.Area = radio; /****************** Buscamos las variables de cada caracteristica desde la ontologia y Relacionan Sensores **********************/ //Conceptos retornados de cada concepto List<string> conceptosE = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesE = new List<Variable>(); //vaiables del Edafotopo string conceptoBuscar = "Edafotopo"; conceptosE = sm.RetornarConceptos(conceptoBuscar,idioma); if(conceptosE != null) foreach(string concepto in conceptosE) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que la pueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesE.Add(variableMedir); } } bio.Edafotopo.Variables=variablesE; //vaiables del Hidrotopo //Conceptos retornados de cada concepto List<string> conceptosH = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesH = new List<Variable>(); conceptoBuscar = "Hidrotopo"; conceptosH = sm.RetornarConceptos(conceptoBuscar,idioma); if (conceptosH != null) foreach(string concepto in conceptosH) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que lapueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesH.Add(variableMedir); } } bio.Hidrotopo.Variables=variablesH; //vaiables del Climátopo //Conceptos retornados de cada concepto List<string> conceptosC = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesC = new List<Variable>(); conceptoBuscar = "Climátopo"; conceptosC = sm.RetornarConceptos(conceptoBuscar,idioma); if (conceptosC != null) foreach(string concepto in conceptosC) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que lapueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesC.Add(variableMedir); } } bio.Climatopo.Variables=variablesC; /****************** Los valores de referencia se los deja,mos al usuario **********************/ return bio; }
private void treeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { if (e.Node is FunctionPointer) { var pointer = e.Node as FunctionPointer; var project = treeView.Nodes[0] as Project; if (!project.Functions.TryGetValue(pointer.Address, out Function function)) { function = new Function { Text = pointer.Address.ToString("X6"), Address = pointer.Address, Project = project, Flags = pointer.Flags }; project.Functions.Add(pointer.Address, function); pointer.Parent.Parent.Nodes.Add(function); } else { History.Push(e.Node); treeView.SelectedNode = function; } } else if (e.Node is VariablePointer) { var pointer = e.Node as VariablePointer; var project = treeView.Nodes[0] as Project; if (!project.Variables.TryGetValue(pointer.Address, out Variable variable)) { variable = new Variable { Text = pointer.Address.ToString("X6"), Address = pointer.Address, Project = project }; project.Variables.Add(pointer.Address, variable); pointer.Parent.Parent.Parent.Nodes[1].Nodes.Add(variable); } else { History.Push(e.Node); treeView.SelectedNode = variable; } } else if (e.Node is TablePointer) { var pointer = e.Node as TablePointer; var project = treeView.Nodes[0] as Project; if (!project.Tables.TryGetValue(pointer.Address, out Table table)) { table = new Table { Text = pointer.Address.ToString("X6"), Address = pointer.Address, Project = project }; project.Tables.Add(pointer.Address, table); pointer.Parent.Parent.Parent.Nodes[0].Nodes.Add(table); } else { History.Push(e.Node); treeView.SelectedNode = table; } } }
private void OnToggleInput(bool val) { data.Value = negate ? !val : val; Variable.SavePlayerPrefs(); }
public FakeTransaction() : base(false) { _session = new Variable(typeof(IFakeSession), "session", this); }
private void Init() { weights_1 = new Variable[2, units_1]; for (int i = 0; i < 2; i++) { for (int j = 0; j < units_1; j++) { weights_1[i, j] = new Variable(Random.Range(-1f, 1f)); } } b_1 = new Variable(0f); weights_2 = new Variable[units_1, units_2]; for (int i = 0; i < units_1; i++) { for (int j = 0; j < units_2; j++) { weights_2[i, j] = new Variable(Random.Range(-1f, 1f)); } } b_2 = new Variable(0f); weights_3 = new Variable[units_2, units_3]; for (int i = 0; i < units_2; i++) { for (int j = 0; j < units_3; j++) { weights_3[i, j] = new Variable(Random.Range(-1f, 1f)); } } b_3 = new Variable(0f); weights_4 = new Variable[units_3, units_4]; for (int i = 0; i < units_3; i++) { for (int j = 0; j < units_4; j++) { weights_4[i, j] = new Variable(Random.Range(-1f, 1f)); } } b_4 = new Variable(0f); weights_5 = new Variable[units_4, units_5]; for (int i = 0; i < units_4; i++) { for (int j = 0; j < units_5; j++) { weights_5[i, j] = new Variable(Random.Range(-1f, 1f)); } } b_5 = new Variable(0f); layer1 = new Variable[batch_size, units_1]; layer2 = new Variable[batch_size, units_2]; layer3 = new Variable[batch_size, units_3]; layer4 = new Variable[batch_size, units_4]; output = new Variable[batch_size, units_5]; loss = new Variable(0); loss.GradValue = 1; }
public Biotipo ObtenerInfoBiotipoContaminacion(GeonameNode nodoBiotipo, string radio, string idioma) { //Objeto del negocio ServiciosMedioAmbientales sm = new ServiciosMedioAmbientales(); //Biotipo generado para presentarlo al usuario Biotipo bio = new Biotipo(); /****************** Obtenemos los Datos Generales del Biotipo **********************/ bio.GeonameId = nodoBiotipo.geonameId; bio.name = nodoBiotipo.Nombre_lugar; bio.CountryName = nodoBiotipo.Nombre_pais; bio.CountryCode = nodoBiotipo.Codigo_pais; bio.AreaImpacto.lat = nodoBiotipo.Latitud; bio.AreaImpacto.lon = nodoBiotipo.Longitud.ToString(); bio.AreaImpacto.Area = radio; /****************** Buscamos las variables de cada caracteristica desde la ontologia y Relacionan Sensores **********************/ //Conceptos retornados de cada concepto List<string> conceptosE = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesE = new List<Variable>(); //vaiables del Aire string conceptoBuscar = "Contaminación del Aire"; conceptosE = sm.RetornarConceptos(conceptoBuscar, idioma); if (conceptosE != null) foreach (string concepto in conceptosE) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que la pueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesE.Add(variableMedir); } } bio.ContaminacionAire.Variables = variablesE; //vaiables del Suelo //Conceptos retornados de cada concepto List<string> conceptosH = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesH = new List<Variable>(); conceptoBuscar = "Contaminación del Suelo"; conceptosH = sm.RetornarConceptos(conceptoBuscar, idioma); if (conceptosH != null) foreach (string concepto in conceptosH) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que lapueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesH.Add(variableMedir); } } bio.ContaminacionSuelo.Variables = variablesH; //vaiables del Agua //Conceptos retornados de cada concepto List<string> conceptosC = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesC = new List<Variable>(); conceptoBuscar = "Contaminación del Agua"; conceptosC = sm.RetornarConceptos(conceptoBuscar, idioma); if (conceptosC != null) foreach (string concepto in conceptosC) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que lapueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesC.Add(variableMedir); } } bio.ContaminacionAgua.Variables = variablesC; //Conceptos retornados de cada concepto List<string> conceptosS = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesS = new List<Variable>(); //vaiables del Sonora conceptoBuscar = "Contaminación Sonora"; conceptosS = sm.RetornarConceptos(conceptoBuscar, idioma); if (conceptosS != null) foreach (string concepto in conceptosS) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que la pueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesS.Add(variableMedir); } } bio.ContaminacionSonora.Variables = variablesS; //vaiables del Termica //Conceptos retornados de cada concepto List<string> conceptosT = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesT = new List<Variable>(); conceptoBuscar = "Contaminación Térmica"; conceptosT = sm.RetornarConceptos(conceptoBuscar, idioma); if (conceptosT != null) foreach (string concepto in conceptosT) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que lapueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesT.Add(variableMedir); } } bio.ContaminacionTermica.Variables = variablesT; //vaiables del Visual //Conceptos retornados de cada concepto List<string> conceptosV = new List<string>(); //Variable relacionadas a buscar mediciones List<Variable> variablesV = new List<Variable>(); conceptoBuscar = "Contaminación Visual"; conceptosV = sm.RetornarConceptos(conceptoBuscar, idioma); if (conceptosV != null) foreach (string concepto in conceptosV) { if (concepto != conceptoBuscar) { Variable variableMedir = new Variable(); variableMedir.Id = concepto; //Buscar Sensores que lapueden medir variableMedir.sensores = sm.RetornarMapaLugar(bio.AreaImpacto.lat, bio.AreaImpacto.lon, concepto, idioma, radio); variablesV.Add(variableMedir); } } bio.ContaminacionVisual.Variables = variablesV; /****************** Los valores de referencia se los deja,mos al usuario **********************/ return bio; }
public VariableReference(Variable variable) : base() { this.Variable = variable; }
private void Predict(Variable[,] x, Variable[] y) { #region L1 for (int i = 0; i < x.GetLength(0); i++) { for (int j = 0; j < weights_1.GetLength(1); j++) { for (int k = 0; k < weights_1.GetLength(0); k++) { layer1[i, j] = layer1[i, j] + x[i, k] * weights_1[k, j]; } layer1[i, j] = layer1[i, j] + b_1; } } for (int i = 0; i < layer1.GetLength(0); i++) { for (int j = 0; j < layer1.GetLength(1); j++) { layer1[i, j] = Variable.ReLU(layer1[i, j]); } } #endregion #region L2 for (int i = 0; i < layer1.GetLength(0); i++) { for (int j = 0; j < weights_2.GetLength(1); j++) { for (int k = 0; k < weights_2.GetLength(0); k++) { layer2[i, j] = layer2[i, j] + layer1[i, k] * weights_2[k, j]; } layer2[i, j] = layer2[i, j] + b_2; } } for (int i = 0; i < layer2.GetLength(0); i++) { for (int j = 0; j < layer2.GetLength(1); j++) { layer2[i, j] = Variable.ReLU(layer2[i, j]); } } #endregion #region L3 for (int i = 0; i < layer2.GetLength(0); i++) { for (int j = 0; j < weights_3.GetLength(1); j++) { for (int k = 0; k < weights_3.GetLength(0); k++) { layer3[i, j] = layer3[i, j] + layer2[i, k] * weights_3[k, j]; } layer3[i, j] = layer3[i, j] + b_3; } } for (int i = 0; i < layer3.GetLength(0); i++) { for (int j = 0; j < layer3.GetLength(1); j++) { layer3[i, j] = Variable.ReLU(layer3[i, j]); } } #endregion #region L4 for (int i = 0; i < layer3.GetLength(0); i++) { for (int j = 0; j < weights_4.GetLength(1); j++) { for (int k = 0; k < weights_4.GetLength(0); k++) { layer4[i, j] = layer4[i, j] + layer3[i, k] * weights_4[k, j]; } layer4[i, j] = layer4[i, j] + b_4; } } for (int i = 0; i < layer4.GetLength(0); i++) { for (int j = 0; j < layer4.GetLength(1); j++) { layer4[i, j] = Variable.ReLU(layer4[i, j]); } } #endregion #region output string results = ""; for (int i = 0; i < layer4.GetLength(0); i++) { for (int j = 0; j < weights_5.GetLength(1); j++) { for (int k = 0; k < weights_5.GetLength(0); k++) { output[i, j] = output[i, j] + layer4[i, k] * weights_5[k, j]; } output[i, j] = output[i, j] + b_5; output[i, j] = new Variable(1f) / (new Variable(1) + Variable.Exp(-output[i, j])); results += output[i, j].Value.ToString() + ", "; } } loss = (y[0] - output[0, 0]) * (y[0] - output[0, 0]) + (y[1] - output[1, 0]) * (y[1] - output[1, 0]) + (y[2] - output[2, 0]) * (y[2] - output[2, 0]) + (y[3] - output[3, 0]) * (y[3] - output[3, 0]); loss = loss / new Variable(4); Debug.Log("Prediction: " + results + " | Loss: " + loss.Value); //var result = // (layer4[0, 0].Value * Mathf.Exp(-b_5.Value - weights_5[0, 0].Value * layer4[0, 0].Value) // * ((1f / ((Mathf.Exp(-b_5.Value - weights_5[0, 0].Value * layer4[0, 0].Value)) + 1f)) - output[0, 0].Value)) / // 2f * ((Mathf.Exp(-b_5.Value - weights_5[0, 0].Value * layer4[0, 0].Value)) + 1f) * ((Mathf.Exp(-b_5.Value - weights_5[0, 0].Value * layer4[0, 0].Value)) + 1f); //Debug.Log(result); //loss.GradValue = 1f; //Debug.Log(weights_5[0, 0].Grad()); #endregion }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public abstract boolean smaller(Variable v) throws JasymcaException; public abstract bool smaller(Variable v);
public Derivative(float Weight, Variable Variable) { this.Weight = Weight; this.Variable = Variable; }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public abstract Algebraic value(Variable var, Algebraic x) throws JasymcaException; public abstract Algebraic value(Variable @var, Algebraic x);
public override IEnumerable <Variable> FindVariables(IMethodVariables chain) { _returnValue = chain.FindVariable(_variableType); yield return(_returnValue); }
public override void TranslateVariable(StringBuilder sb, Variable variable) { sb.Append("v_"); sb.Append(variable.Name); }
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: //ORIGINAL LINE: public abstract Algebraic deriv(Variable x) throws JasymcaException; public abstract Algebraic deriv(Variable x);
public override Cmd VisitCallCmd(CallCmd node) { HashSet<Variable> inVars = new HashSet<Variable>(); for (int i = 0; i < node.Proc.InParams.Count; i++) { Variable formal = node.Proc.InParams[i]; string domainName = FindDomainName(formal); if (domainName == null) continue; IdentifierExpr actual = node.Ins[i] as IdentifierExpr; if (actual == null) { Error(node.Ins[i], $"Only variable can be passed to linear parameter {formal.Name}"); continue; } string actualDomainName = FindDomainName(actual.Decl); if (actualDomainName == null) { Error(actual, $"Only a linear argument can be passed to linear parameter {formal.Name}"); continue; } if (domainName != actualDomainName) { Error(actual, "The domains of formal and actual parameters must be the same"); continue; } if (actual.Decl is GlobalVariable) { Error(actual, "Only local linear variable can be an actual input parameter of a procedure call"); continue; } if (inVars.Contains(actual.Decl)) { Error(node, $"Linear variable {actual.Decl.Name} can occur only once as an input parameter"); continue; } inVars.Add(actual.Decl); } for (int i = 0; i < node.Proc.OutParams.Count; i++) { IdentifierExpr actual = node.Outs[i]; string actualDomainName = FindDomainName(actual.Decl); if (actualDomainName == null) continue; Variable formal = node.Proc.OutParams[i]; string domainName = FindDomainName(formal); if (domainName == null) { Error(node, "Only a linear variable can be passed to a linear parameter"); continue; } if (domainName != actualDomainName) { Error(node, "The domains of formal and actual parameters must be the same"); continue; } if (actual.Decl is GlobalVariable) { Error(node, "Only local linear variable can be actual output parameter of a procedure call"); continue; } } return base.VisitCallCmd(node); }
public override bool VisitVariableDecl(Variable variable) { CheckForSymbols(variable); return(base.VisitVariableDecl(variable)); }
/// <summary> /// The example shows /// - how to load model. /// - how to prepare input data for a batch of samples. /// - how to prepare input and output data map. /// - how to evaluate a model. /// - how to retrieve evaluation result and retrieve output data in dense format. /// </summary> /// <param name="device">Specify on which device to run the evaluation.</param> public static void EvaluationBatchOfImages(DeviceDescriptor device) { try { Console.WriteLine("\n===== Evaluate batch of images ====="); string modelFilePath = "resnet20.dnn"; // This program uses images from the CIFAR-10 dataset for evaluation. // Please see README.md in <CNTK>/Examples/Image/DataSets/CIFAR-10 about how to download the CIFAR-10 dataset. var imageList = new List <string>() { "00000.png", "00001.png", "00002.png" }; foreach (var image in imageList) { ThrowIfFileNotExist(image, string.Format("Error: The sample image '{0}' does not exist. Please see README.md in <CNTK>/Examples/Image/DataSets/CIFAR-10 about how to download the CIFAR-10 dataset.", image)); } ThrowIfFileNotExist(modelFilePath, string.Format("Error: The model '{0}' does not exist. Please follow instructions in README.md in <CNTK>/Examples/Image/Classification/ResNet to create the model.", modelFilePath)); // Load the model. // The model resnet20.dnn is trained by <CNTK>/Examples/Image/Classification/ResNet/Python/Models/TrainResNet_CIFAR10.py // Please see README.md in <CNTK>/Examples/Image/Classification/ResNet about how to train the model. Function modelFunc = Function.Load(modelFilePath, device); // Get input variable. The model has only one single input. // The same way described above for output variable can be used here to get input variable by name. Variable inputVar = modelFunc.Arguments.Single(); // Get shape data for the input variable NDShape inputShape = inputVar.Shape; int imageWidth = inputShape[0]; int imageHeight = inputShape[1]; int imageChannels = inputShape[2]; int imageSize = inputShape.TotalSize; // The model has only one output. // If the model have more than one output, use the following way to get output variable by name. // Variable outputVar = modelFunc.Outputs.Where(variable => string.Equals(variable.Name, outputName)).Single(); Variable outputVar = modelFunc.Output; var inputDataMap = new Dictionary <Variable, Value>(); var outputDataMap = new Dictionary <Variable, Value>(); Bitmap bmp, resized; List <float> resizedCHW; var seqData = new List <float>(); for (int sampleIndex = 0; sampleIndex < imageList.Count; sampleIndex++) { bmp = new Bitmap(Bitmap.FromFile(imageList[sampleIndex])); resized = bmp.Resize((int)imageWidth, (int)imageHeight, true); resizedCHW = resized.ParallelExtractCHW(); // Aadd this sample to the data buffer. seqData.AddRange(resizedCHW); } // Create Value for the batch data. var inputVal = Value.CreateBatch(inputVar.Shape, seqData, device); // Create input data map. inputDataMap.Add(inputVar, inputVal); // Create output data map. Using null as Value to indicate using system allocated memory. // Alternatively, create a Value object and add it to the data map. outputDataMap.Add(outputVar, null); // Evaluate the model against the batch input modelFunc.Evaluate(inputDataMap, outputDataMap, device); // Retrieve the evaluation result. var outputVal = outputDataMap[outputVar]; var outputData = outputVal.GetDenseData <float>(outputVar); // Output result PrintOutput(outputVar.Shape.TotalSize, outputData); } catch (Exception ex) { Console.WriteLine("Error: {0}\nCallStack: {1}\n Inner Exception: {2}", ex.Message, ex.StackTrace, ex.InnerException != null ? ex.InnerException.Message : "No Inner Exception"); throw ex; } }
[Trait("Category", "OpenBug")] // Test failing with AutomatonTooLarge due to determinization added to SetToProduct in change 47614. Increasing max states to 1M does not fix the issue public void PropertyInferencePerformanceTest() { Rand.Restart(777); var namesData = new[] { "Alice", "Bob", "Charlie", "Eve", "Boris", "John" }; var valueData = new[] { "sender", "receiver", "attacker", "eavesdropper", "developer", "researcher" }; var templatesData = new[] { "{0} is {1}", "{0} is known as {1}", "{1} is a role of {0}", "{0} -- {1}", "{0} aka {1}" }; var textsData = new string[10]; for (int i = 0; i < textsData.Length; ++i) { int entityIndex = Rand.Int(namesData.Length); int templateIndex = Rand.Int(templatesData.Length); textsData[i] = string.Format(templatesData[templateIndex], namesData[entityIndex], valueData[entityIndex]); } var entity = new Range(namesData.Length).Named("entity"); var template = new Range(templatesData.Length).Named("template"); var text = new Range(textsData.Length).Named("text"); var entityNames = Variable.Array <string>(entity).Named("entityNames"); entityNames[entity] = Variable.Random(StringDistribution.Capitalized()).ForEach(entity); var entityValues = Variable.Array <string>(entity).Named("entityValues"); entityValues[entity] = Variable.Random(StringDistribution.Lower()).ForEach(entity); StringDistribution templatePriorMiddle = StringDistribution.ZeroOrMore(DiscreteChar.OneOf('{', '}').Complement()); StringDistribution templatePrior = StringDistribution.OneOf( StringDistribution.String("{0} ") + templatePriorMiddle + StringDistribution.String(" {1}"), StringDistribution.String("{1} ") + templatePriorMiddle + StringDistribution.String(" {0}")); var templates = Variable.Array <string>(template).Named("templates"); templates[template] = Variable.Random(templatePrior).ForEach(template); var texts = Variable.Array <string>(text).Named("texts"); using (Variable.ForEach(text)) { var entityIndex = Variable.DiscreteUniform(entity).Named("entityIndex"); var templateIndex = Variable.DiscreteUniform(template).Named("templateIndex"); using (Variable.Switch(entityIndex)) using (Variable.Switch(templateIndex)) { texts[text] = Variable.StringFormat(templates[templateIndex], entityNames[entityIndex], entityValues[entityIndex]); } } texts.ObservedValue = textsData; var engine = new InferenceEngine(); engine.ShowProgress = false; engine.OptimiseForVariables = new[] { entityNames, entityValues }; engine.Compiler.RecommendedQuality = QualityBand.Experimental; // TODO: get this test to work with parallel for loops. engine.Compiler.UseParallelForLoops = false; engine.NumberOfIterations = 1; ProfileAction( () => { Console.WriteLine(engine.Infer <StringDistribution[]>(entityNames)[0]); Console.WriteLine(engine.Infer <StringDistribution[]>(entityValues)[0]); }, 1); }
public StreamFieldVisitor(Variable variable, Expression index = null) : base(false, false) { typeInference = variable; arrayIndex = index; }
private HashSet<Variable> PropagateAvailableLinearVarsAcrossBlock(Block b) { HashSet<Variable> start = new HashSet<Variable>(availableLinearVars[b]); foreach (Cmd cmd in b.Cmds) { if (cmd is AssignCmd assignCmd) { for (int i = 0; i < assignCmd.Lhss.Count; i++) { if (FindDomainName(assignCmd.Lhss[i].DeepAssignedVariable) == null) continue; IdentifierExpr ie = assignCmd.Rhss[i] as IdentifierExpr; if (!start.Contains(ie.Decl)) { Error(ie, "unavailable source for a linear read"); } else { start.Remove(ie.Decl); } } foreach (AssignLhs assignLhs in assignCmd.Lhss) { if (FindDomainName(assignLhs.DeepAssignedVariable) == null) continue; start.Add(assignLhs.DeepAssignedVariable); } } else if (cmd is CallCmd callCmd) { foreach (GlobalVariable g in globalVarToDomainName.Keys.Except(start)) { Error(cmd, $"Global variable {g.Name} must be available at a call"); } for (int i = 0; i < callCmd.Proc.InParams.Count; i++) { Variable param = callCmd.Proc.InParams[i]; if (FindDomainName(param) == null) continue; IdentifierExpr ie = callCmd.Ins[i] as IdentifierExpr; LinearKind paramKind = FindLinearKind(param); if (start.Contains(ie.Decl)) { if (callCmd.IsAsync || paramKind == LinearKind.LINEAR_IN) { start.Remove(ie.Decl); } } else { if (paramKind == LinearKind.LINEAR_OUT) { start.Add(ie.Decl); } else { Error(ie, "unavailable source for a linear read"); } } } AddAvailableVars(callCmd, start); availableLinearVars[callCmd] = new HashSet<Variable>(start); } else if (cmd is ParCallCmd parCallCmd) { foreach (GlobalVariable g in globalVarToDomainName.Keys.Except(start)) { Error(cmd, $"Global variable {g.Name} must be available at a call"); } foreach (CallCmd parCallCallCmd in parCallCmd.CallCmds) { for (int i = 0; i < parCallCallCmd.Proc.InParams.Count; i++) { Variable param = parCallCallCmd.Proc.InParams[i]; if (FindDomainName(param) == null) continue; IdentifierExpr ie = parCallCallCmd.Ins[i] as IdentifierExpr; LinearKind paramKind = FindLinearKind(param); if (start.Contains(ie.Decl)) { if (paramKind == LinearKind.LINEAR_IN) { start.Remove(ie.Decl); } } else { if (paramKind == LinearKind.LINEAR_OUT) { start.Add(ie.Decl); } else { Error(ie, "unavailable source for a linear read"); } } } } AddAvailableVars(parCallCmd, start); availableLinearVars[parCallCmd] = new HashSet<Variable>(start); } else if (cmd is HavocCmd havocCmd) { foreach (IdentifierExpr ie in havocCmd.Vars) { if (FindDomainName(ie.Decl) == null) continue; start.Remove(ie.Decl); } } else if (cmd is YieldCmd) { foreach (GlobalVariable g in globalVarToDomainName.Keys.Except(start)) { Error(cmd, $"Global variable {g.Name} must be available at a yield"); } availableLinearVars[cmd] = new HashSet<Variable>(start); } } return start; }
/// <summary> /// The example shows /// - how to evaluate multiple sample requests in parallel. /// </summary> /// <param name="device">Specify on which device to run the evaluation.</param> public static void EvaluateMultipleImagesInParallel(DeviceDescriptor device) { Console.WriteLine("\n===== Evaluate multiple images in parallel ====="); string modelFilePath = "resnet20.dnn"; // This program uses images from the CIFAR-10 dataset for evaluation. // Please see README.md in <CNTK>/Examples/Image/DataSets/CIFAR-10 about how to download the CIFAR-10 dataset. var imageList = new List <string>() { "00000.png", "00001.png", "00002.png", "00003.png", "00004.png" }; foreach (var image in imageList) { ThrowIfFileNotExist(image, string.Format("Error: The sample image '{0}' does not exist. Please see README.md in <CNTK>/Examples/Image/DataSets/CIFAR-10 about how to download the CIFAR-10 dataset.", image)); } ThrowIfFileNotExist(modelFilePath, string.Format("Error: The model '{0}' does not exist. Please follow instructions in README.md in <CNTK>/Examples/Image/Classification/ResNet to create the model.", modelFilePath)); int maximalNumOfParallelRequests = 3; BlockingCollection <Function> Models = new BlockingCollection <Function>(); // Load and clone the model. // The model resnet20.dnn is trained by <CNTK>/Examples/Image/Classification/ResNet/Python/Models/TrainResNet_CIFAR10.py // Please see README.md in <CNTK>/Examples/Image/Classification/ResNet about how to train the model. var rootFunc = Function.Load(modelFilePath, device); Models.Add(rootFunc); // It is not thread-safe to perform concurrent evaluation requests using the same model function. // Use clone() to create copies of model function for parallel evaluation. // ParameterCloningMethod.Share specifies that model parameters are shared between cloned model functions, while // each model function instance has its own private state for evaluation. for (int i = 1; i < maximalNumOfParallelRequests; i++) { Models.Add(rootFunc.Clone(ParameterCloningMethod.Share)); } // Get shape data for the input variable var input = rootFunc.Arguments.Single(); NDShape inputShape = input.Shape; int imageWidth = inputShape[0]; int imageHeight = inputShape[1]; int imageChannels = inputShape[2]; int imageSize = inputShape.TotalSize; Object lockObj = new object(); // Start to evaluate samples in parallel. // If there are more evaluation requests than the number of available model function instances, some evaluation // requests will have to wait for a free model function instance. Console.WriteLine(string.Format("Evaluate {0} images in parallel using {1} model instances.", imageList.Count, maximalNumOfParallelRequests)); Parallel.ForEach(imageList, new ParallelOptions() { MaxDegreeOfParallelism = imageList.Count }, (image) => { var evaluatorFunc = Models.Take(); try { Variable outputVar = evaluatorFunc.Output; Variable inputVar = evaluatorFunc.Arguments.Single(); var inputDataMap = new Dictionary <Variable, Value>(); var outputDataMap = new Dictionary <Variable, Value>(); Bitmap bmp = new Bitmap(Bitmap.FromFile(image)); var resized = bmp.Resize((int)imageWidth, (int)imageHeight, true); List <float> resizedCHW = resized.ParallelExtractCHW(); // Create input data map var inputVal = Value.CreateBatch(inputVar.Shape, resizedCHW, device); inputDataMap.Add(inputVar, inputVal); // Create output data map. Using null as Value to indicate using system allocated memory. // Alternatively, create a Value object and add it to the data map. outputDataMap.Add(outputVar, null); // Start evaluation on the device evaluatorFunc.Evaluate(inputDataMap, outputDataMap, device); // Get evaluate result as dense output var outputVal = outputDataMap[outputVar]; var outputData = outputVal.GetDenseData <float>(outputVar); // Serialize output lock (lockObj) { Console.WriteLine(string.Format("Evaluation result for {0}:", image)); PrintOutput(outputVar.Shape.TotalSize, outputData); } } finally { Models.Add(evaluatorFunc); } }); }
public override Variable VisitVariable(Variable node) { CivlAttributes.RemoveLinearAttributes(node); return base.VisitVariable(node); }
public void ShouldSolveSystemWith1EquationAnd2Variables() { //x+y=10 x=6; y=4 //x-y=2 var variableX = new Variable("x"); var variableY = new Variable("y"); var left1FirstEq = new Expression(1, variableX); var left2FirstEq = new Expression(1, variableY); var rightFirstEq = new Expression(10, Variable.NULL); var left1SecondEq = new Expression(1, variableX); var left2SecondEq = new Expression(-1, variableY); var rightSecondEq = new Expression(2, Variable.NULL); var firstEquation = new Equation(new List<Expression>() { left1FirstEq, left2FirstEq }, rightFirstEq); var secondEquation = new Equation(new List<Expression>() {left1SecondEq, left2SecondEq}, rightSecondEq); var target = new SystemOfEquations(new List<Equation>() {firstEquation, secondEquation}); target.Solve(); var resultX = variableX.Value; var resultY = variableY.Value; Assert.AreEqual(1, resultX.Count); Assert.AreEqual(1, resultY.Count); Assert.AreEqual(Variable.NULL, resultX.First().Variable); Assert.AreEqual(6, resultX.First().Coefficient); Assert.AreEqual(Variable.NULL, resultY.First().Variable); Assert.AreEqual(4, resultY.First().Coefficient); }