Exemple #1
0
        /// <summary>
        /// Invoke this hook with a certain parameter registry.
        /// </summary>
        /// <param name="registry">The registry containing the required values for this hook's execution.</param>
        /// <param name="resolver">A helper resolver for complex registry entries (automatically cached).</param>
        public override void SubInvoke(IRegistry registry, IRegistryResolver resolver)
        {
            int epoch     = registry.Get <int>("epoch");
            int iteration = registry.Get <int>("iteration");

            Report(epoch, iteration);
        }
        protected virtual void SetupTest()
        {
            _reg = new Registry <IModel>();
            _reg.Bind <Service.ICardTemplateService, Service.Impl.CardTemplateService>(new Service.Impl.CardTemplateService());
            _reg.Bind <IBoardModel, BoardModel>(new BoardModel(8, 8));
            _reg.Bind <IArbiterModel, ArbiterModel>(new ArbiterModel());
            _reg.Bind <IWhitePlayerModel, WhitePlayerModel>();
            _reg.Bind <IBlackPlayerModel, BlackPlayerModel>();
            _reg.Bind <ICardModel, CardModel>();
            _reg.Bind <IDeckModel, MockDeck>();
            _reg.Bind <IHandModel, MockHand>();
            _reg.Bind <IPieceModel, PieceModel>();
            _reg.Bind <IEndTurnButtonModel, EndTurnButtonModel>();
            _reg.Resolve();

            _board   = _reg.Get <IBoardModel>();
            _arbiter = _reg.Get <IArbiterModel>();
            _white   = _reg.Get <IWhitePlayerModel>();
            _black   = _reg.Get <IBlackPlayerModel>();

            foreach (var model in _reg.Instances.ToList())
            {
                model.PrepareModels();
            }
        }
Exemple #3
0
        /// <inheritdoc />
        public FullyConnectedLayer(string name, IRegistry parameters, IComputationHandler handler) : base(name, parameters, handler)
        {
            int size      = parameters.Get <int>("size");
            int inputSize = parameters.Get <int>("default_input_size");

            parameters["weights"] = handler.NDArray(inputSize, size);
            parameters["biases"]  = handler.NDArray(size);

            TrainableParameters = new[] { "weights", "biases" };
        }
Exemple #4
0
        public Resource(ResourceData data, IRegistry registry) : base(data, registry)
        {
            _qty = data.Value;
            try {
                Capacity = registry.Get <IStat>(data.Capacity);
            } catch (StatNotFoundException) {
                throw new StatNotFoundException(data.Capacity + " (Resource::.output) ");
            }

            try {
                Output = registry.Get <IStat>(data.Output);
            } catch (StatNotFoundException) {
                throw new StatNotFoundException(data.Output + " (Resource::.output) ");
            }
        }
Exemple #5
0
        ///<inheritdoc cref="FromPrefab{TIView}(UnityEngine.Object)"/>
        public TIView FromPrefab <TIView, TIAgent, TIModel>(Object prefab, IRegistry <TIModel> models, IRegistry <TIAgent> agents = null)
            where TIView : class, IViewBase
            where TIAgent : class, IAgent, IHasDestroyHandler <TIAgent>, IHasRegistry <TIAgent>
            where TIModel : class, IModel, IHasDestroyHandler <TIModel>, IHasRegistry <TIModel>
        {
            Assert.IsNotNull(prefab);
            var view = Object.Instantiate(prefab) as TIView;

            Assert.IsNotNull(view);
            view = Prepare(Inject(typeof(TIView), view)) as TIView;
            Assert.IsNotNull(view);
            var model = models.Get <TIModel>();

            if (agents != null)
            {
                TIAgent agent = agents.Get <TIAgent>(model);
                view.SetAgent(agent);
                agent.AddSubscriptions();
                agent.BaseModel.AddSubscriptions();
                view.AddSubscriptions();
            }

            Assert.IsTrue(view.IsValid);
            return(view);
        }
Exemple #6
0
 public OutputLayer(string name, IRegistry parameters, IComputationHandler handler) : base(name, parameters, handler)
 {
     // external to indicate that these parameters are not only external (which should already be indicate with the InputsExternal flag in the layer construct and buffer)
     //	but also that they mark the boundaries of the entire network (thereby external to the network, not only external as in external source)
     //	default is the pass-through to next layer
     ExpectedOutputs = new[] { parameters.Get <string>("external_output_alias"), "default" };
 }
Exemple #7
0
        public ElementwiseLayer(string name, IRegistry parameters, IComputationHandler handler) : base(name, parameters, handler)
        {
            int size = parameters.Get <int>("size");

            parameters["weights"] = handler.NDArray(size);
            parameters["bias"]    = handler.Number(0);

            TrainableParameters = new[] { "weights", "bias" };
        }
Exemple #8
0
        /// <summary>
        /// Get the current interval of a certain time scale out of a registry.
        /// Note: Time scale can only be epoch or iteration.
        /// </summary>
        /// <param name="registry">The registry.</param>
        /// <param name="timeScale">The time scale.</param>
        /// <returns>The current interval of the given time scale as it is in the given registry.</returns>
        public static int GetCurrentInterval(IRegistry registry, TimeScale timeScale)
        {
            if (registry == null)
            {
                throw new ArgumentNullException(nameof(registry));
            }

            if (timeScale == TimeScale.Epoch)
            {
                return(registry.Get <int>("epoch"));
            }
            else if (timeScale == TimeScale.Iteration)
            {
                return(registry.Get <int>("iteration"));
            }
            else
            {
                throw new ArgumentException($"Cannot get current interval of time scale {timeScale}, must be either {nameof(TimeScale.Epoch)} or {nameof(TimeScale.Iteration)}.");
            }
        }
Exemple #9
0
 public Multistat(MultistatData data, IRegistry registry) : base(data, registry)
 {
     if (data.Stats != null && data.Stats.Length > 0)
     {
         List <IStat> list = new List <IStat>();
         foreach (string code in data.Stats)
         {
             list.Add(registry.Get <IStat>(code));
         }
         Stats = list.ToArray();
     }
 }
        public override bool CheckCriteria(IRegistry registry, IRegistryResolver resolver)
        {
            string parameter        = ParameterRegistry.Get <string>("parameter_identifier");
            object rawValue         = SimpleDirectEntries[0] ? registry.Get(parameter) : resolver.ResolveGetSingle <object>(parameter);
            double value            = (double)Convert.ChangeType(rawValue, typeof(double));
            bool   thresholdReached = _InternalThresholdReached(value, ParameterRegistry.Get <double>("threshold_value"), ParameterRegistry.Get <ComparisonTarget>("target"));
            bool   fire             = thresholdReached && (!ParameterRegistry.Get <bool>("last_check_met") || ParameterRegistry.Get <bool>("fire_continously"));

            ParameterRegistry["last_check_met"] = thresholdReached;

            return(fire);
        }
Exemple #11
0
        public Stat(StatData data, IRegistry registry) : base(data, registry)
        {
            // process for serialization
            if (data.Dependencies != null)
            {
                foreach (StatData.Dependency dep in data.Dependencies)
                {
                    IStat stat = registry.Get <IStat>(dep.Code);
                    _dependencies.Add(stat, dep.Value);
                }
            }

            ResetModifierTotals();
        }
Exemple #12
0
        /// <summary>
        /// Get the total cost from a certain network using a certain computation handler and put the relevant information in the cost registry (total, partial, importances).
        /// </summary>
        /// <param name="network">The network to get the costs from.</param>
        /// <param name="handler">The handler to use.</param>
        /// <param name="costRegistry">The registry to put relevant information in.</param>
        /// <returns>The total cost of the given network (0.0 if none).</returns>
        protected virtual INumber GetTotalCost(INetwork network, IComputationHandler handler, IRegistry costRegistry)
        {
            INumber totalCost = handler.Number(0);

            foreach (ILayerBuffer layerBuffer in network.YieldExternalOutputsLayerBuffers())
            {
                if (layerBuffer.Outputs.ContainsKey(ExternalCostAlias))
                {
                    IRegistry externalCostRegistry = layerBuffer.Outputs[ExternalCostAlias];

                    INumber partialCost       = externalCostRegistry.Get <INumber>("cost");
                    double  partialImportance = externalCostRegistry.Get <double>("importance");

                    costRegistry["partial_" + layerBuffer.Layer.Name] = partialCost.GetValueAs <double>();
                    costRegistry["partial_" + layerBuffer.Layer.Name + "_importance"] = partialImportance;

                    totalCost = handler.Add(totalCost, handler.Multiply(partialCost, partialImportance));
                }
            }

            costRegistry["total"] = totalCost.GetValueAs <double>();

            return(totalCost);
        }
Exemple #13
0
        public object Resolve(string key)
        {
            if (!_registry.Contains(key))
            {
                throw new InvalidOperationException(
                          string.Format(@"Component cannot be 
                            resolved from key {0} because nothing was registered under that name.", key));
            }
            var reg          = _registry.Get(key);
            var resolverList = (IEnumerable <IResolveObjects>)InternalResolver
                               .ResolveAll(typeof(IResolveObjects));
            var resolver = resolverList.ToList().Find(r => r.CanProcess(reg.ResolutionType));

            return(resolver.Resolve(reg));
        }
Exemple #14
0
        ///<inheritdoc cref="FromPrefab{TIView}(UnityEngine.Object)"/>
        public TIView FromPrefab <TIView, TIAgent>(Object prefab, IRegistry <TIAgent> agents)
            where TIView : class, IViewBase
            where TIAgent : class, IAgent, IHasDestroyHandler <TIAgent>, IHasRegistry <TIAgent>
        {
            var view = FromPrefab <TIView>(prefab);

            Assert.IsNotNull(view);
            var agent = agents.Get <TIAgent>();

            view.SetAgent(agent);
            view.AddSubscriptions();
            agent.AddSubscriptions();
            agent.BaseModel.AddSubscriptions();
            Assert.IsTrue(view.IsValid);
            return(view);
        }
        public override bool CheckCriteria(IRegistry registry, IRegistryResolver resolver)
        {
            ExtremaTarget target = ParameterRegistry.Get <ExtremaTarget>("target");
            string        parameter = ParameterRegistry.Get <string>("parameter_identifier");
            double        value = SimpleDirectEntries[0] ? registry.Get <double>(parameter) : resolver.ResolveGetSingle <double>(parameter);
            double        currentExtremum = ParameterRegistry.Get <double>("current_extremum");
            bool          reachedExtremum = target == ExtremaTarget.Min && value <currentExtremum || target == ExtremaTarget.Max && value> currentExtremum;

            if (double.IsNaN(currentExtremum) || reachedExtremum)
            {
                ParameterRegistry["current_extremum"] = value;

                return(true);
            }

            return(false);
        }
        private void AddMatchingIdentifiersFromRegistryTree(int hierarchyLevel, int lastHierarchySearchLevel, IRegistry currentRootAtLevel, string currentFullIdentifier, string[] parsedMatchIdentifierParts, ISet <string>[] conditionalTagsPerLevel, MatchIdentifierRequestCacheEntry newCacheEntry)
        {
            Regex regex = new Regex(parsedMatchIdentifierParts[hierarchyLevel]);

            bool noneMatched = true;

            foreach (string identifier in currentRootAtLevel.Keys.ToArray())             // TODO ugly hack, toarray is inefficient and is just to prevent "random" concurrent modification exception
            {
                if (regex.IsMatch(identifier))
                {
                    object value = currentRootAtLevel.Get(identifier);

                    if (hierarchyLevel < lastHierarchySearchLevel && value is IRegistry)
                    {
                        IRegistry subRegistry = (IRegistry)value;

                        if (RegistryMatchesAllTags(subRegistry, conditionalTagsPerLevel[hierarchyLevel]))
                        {
                            string nextFullIdentifier = String.IsNullOrEmpty(currentFullIdentifier) ? identifier : (currentFullIdentifier + "." + identifier);

                            AddMatchingIdentifiersFromRegistryTree(hierarchyLevel + 1, lastHierarchySearchLevel, subRegistry, nextFullIdentifier, parsedMatchIdentifierParts, conditionalTagsPerLevel, newCacheEntry);
                        }
                    }
                    else if (hierarchyLevel == lastHierarchySearchLevel)
                    {
                        if (value is IRegistry && !RegistryMatchesAllTags((IRegistry)value, conditionalTagsPerLevel[hierarchyLevel]))
                        {
                            continue;
                        }

                        string globalFullIdentifier = (String.IsNullOrEmpty(currentFullIdentifier) ? "" : currentFullIdentifier + ".") + identifier;

                        newCacheEntry.FullMatchedIdentifierRegistries.Add(globalFullIdentifier, currentRootAtLevel);
                        newCacheEntry.FullMatchedIdentifierLocals.Add(globalFullIdentifier, identifier);
                    }

                    noneMatched = false;
                }
            }

            if (noneMatched && hierarchyLevel == lastHierarchySearchLevel && !newCacheEntry.LastUnmatchedIdentifierRegistries.ContainsKey(currentFullIdentifier))
            {
                // keep last unmatched identifiers in case there is a (direct) resolve set
                newCacheEntry.LastUnmatchedIdentifierRegistries.Add(currentFullIdentifier, currentRootAtLevel);
            }
        }
Exemple #17
0
        /// <summary>
        /// Get a registry copy containing a copy of given required values.
        /// </summary>
        /// <param name="registry">The registry.</param>
        /// <param name="resolvedRegistryEntries">The RESOLVED registry entries.</param>
        /// <returns>A registry copy containing a copy of given required values.</returns>
        public static IRegistry GetRegistryCopyForResolvedEntries(IRegistry registry, ISet <string> resolvedRegistryEntries)
        {
            IRegistry rootCopy = new Registry(tags: registry.Tags.ToArray());

            foreach (string entry in resolvedRegistryEntries)
            {
                string[] parts = entry.Split('.');

                IRegistry currentRoot     = registry;
                IRegistry currentRootCopy = rootCopy;

                for (int i = 0; i < parts.Length - 1; i++)
                {
                    string part = parts[i];

                    if (!currentRoot.ContainsKey(part))
                    {
                        throw new InvalidOperationException($"Cannot access non-existing registry \"{part}\" from full entry \"{entry}\" (level {i}).");
                    }

                    IRegistry nextRoot = currentRoot[part] as IRegistry;

                    if (nextRoot == null)
                    {
                        throw new InvalidOperationException($"Cannot access non-registry entry \"{part}\" from full entry \"{entry}\" (level {i}), should be instance of {nameof(IRegistry)}.");
                    }

                    if (!currentRootCopy.ContainsKey(part))
                    {
                        currentRootCopy[part] = new Registry(parent: currentRootCopy, tags: nextRoot.Tags.ToArray());
                        currentRootCopy       = currentRootCopy.Get <IRegistry>(part);
                    }

                    currentRoot = nextRoot;
                }

                string lastPart    = parts[parts.Length - 1];
                object copiedValue = RegistryUtils.DeepestCopy(currentRoot[lastPart]);

                currentRootCopy[lastPart] = copiedValue;
            }

            return(rootCopy);
        }
        /// <summary>
        /// Try to retrieve a value from this source (if existent).
        /// </summary>
        /// <typeparam name="T">The type of the value that will be retrieved.</typeparam>
        /// <param name="key">The key of the value.</param>
        /// <param name="val">The value itself that will be assigned if it could be retrieved, <c>null</c> otherwise.</param>
        /// <returns><c>True</c> if the source could retrieve given key, <c>false</c> otherwise.</returns>
        public bool TryGet <T>(string key, out T val)
        {
            IRegistry         values   = (IRegistry)ParameterRegistry[ValueIdentifier];
            IRegistryResolver resolver = values.Get <IRegistryResolver>(RegistryResolver);

            //TODO: validate lock requirement, probably it is required
            lock (values)
            {
                T[] vals = resolver.ResolveGet <T>(key);

                if (vals.Length > 0)
                {
                    val = vals[0];
                    return(true);
                }

                val = default(T);
                return(false);
            }
        }
Exemple #19
0
        /// <summary>
        /// Invoke this hook with a certain parameter registry.
        /// </summary>
        /// <param name="registry">The registry containing the required values for this hook's execution.</param>
        /// <param name="resolver">A helper resolver for complex registry entries (automatically cached).</param>
        public override void SubInvoke(IRegistry registry, IRegistryResolver resolver)
        {
            string[] valueIdentifiers = ParameterRegistry.Get <string[]>("value_identifiers");

            IDictionary <string, object> valuesByIdentifier = ParameterRegistry.Get <IDictionary <string, object> >("value_buffer");

            valuesByIdentifier.Clear();

            for (int i = 0; i < valueIdentifiers.Length; i++)
            {
                string[] resolvedIdentifiers;
                object[] values = resolver.ResolveGet <object>(valueIdentifiers[i], out resolvedIdentifiers);

                for (int y = 0; y < resolvedIdentifiers.Length; y++)
                {
                    valuesByIdentifier.Add(resolvedIdentifiers[y], values[y]);
                }
            }

            ReportValues(valuesByIdentifier, ParameterRegistry.Get <bool>("report_epoch_iteration"), registry.Get <int>("epoch"), registry.Get <int>("iteration"));
        }
Exemple #20
0
 /// <summary>
 /// Create a base layer with a certain unique name.
 /// </summary>
 /// <param name="name">The unique name of this layer.</param>
 /// <param name="parameters">The parameters to this layer.</param>
 /// <param name="handler">The handler to use for ndarray parameter creation.</param>
 public DropoutLayer(string name, IRegistry parameters, IComputationHandler handler) : base(name, parameters, handler)
 {
     parameters["dropout_mask"] = handler.NDArray(parameters.Get <int>("size"));
 }
Exemple #21
0
 /// <summary>
 /// Create a base layer with a certain unique name.
 /// </summary>
 /// <param name="name">The unique name of this layer.</param>
 /// <param name="parameters">The parameters to this layer.</param>
 /// <param name="handler">The handler to use for ndarray parameter creation.</param>
 protected BaseCostLayer(string name, IRegistry parameters, IComputationHandler handler) : base(name, parameters, handler)
 {
     ExpectedInputs  = new[] { parameters.Get <string>("external_targets_alias"), "default" };
     ExpectedOutputs = new[] { parameters.Get <string>("external_cost_alias") };
 }
Exemple #22
0
        /// <summary>
        /// Invoke this hook with a certain parameter registry.
        /// </summary>
        /// <param name="registry">The registry containing the required values for this hook's execution.</param>
        /// <param name="resolver">A helper resolver for complex registry entries (automatically cached).</param>
        public override void SubInvoke(IRegistry registry, IRegistryResolver resolver)
        {
            string[] accumulatedIdentifiers = ParameterRegistry.Get <string[]>("accumulated_identifiers");
            string[] valueIdentifiers       = ParameterRegistry.Get <string[]>("value_identifiers");

            IDictionary <string, object> valuesByIdentifier = ParameterRegistry.Get <IDictionary <string, object> >("value_buffer");

            for (int i = 0; i < valueIdentifiers.Length; i++)
            {
                // TODO let callee decide if it's a number (double) / something else
                object value = resolver.ResolveGetSingle <double>(accumulatedIdentifiers[i]);

                valuesByIdentifier[valueIdentifiers[i]] = value;
            }

            ReportValues(valuesByIdentifier, ParameterRegistry.Get <bool>("report_epoch_iteration"), registry.Get <int>("epoch"), registry.Get <int>("iteration"));
        }
Exemple #23
0
 /// <summary>
 /// Gets an environment with a given name, if previously created (null otherwise).
 /// </summary>
 /// <param name="environmentName">The environment name.</param>
 /// <returns>The existing with the given name or null.</returns>
 public static SigmaEnvironment Get(string environmentName)
 {
     return(ActiveSigmaEnvironments.Get <SigmaEnvironment>(environmentName));
 }
Exemple #24
0
        public override void Invoke(IRegistry reg, Stack <object> stack)
        {
            var obj = stack.Pop();

            stack.Push(_fun(reg.Get <T>(obj)));
        }
Exemple #25
0
 private string GetInstalledFilePath()
 {
     return(_registry.Get(FilePathLocationRegistry, FilePathLocationRegistryKey));
 }