예제 #1
0
        public TaskState( NBTag tag )
        {
            if( FormatVersion != tag["FormatVersion"].GetInt() ) throw new FormatException( "Incompatible format." );
            Shapes = tag["Shapes"].GetInt();
            Vertices = tag["Vertices"].GetInt();
            ImprovementCounter = tag["ImprovementCounter"].GetInt();
            MutationCounter = tag["MutationCounter"].GetInt();
            TaskStart = DateTime.UtcNow.Subtract( TimeSpan.FromTicks( tag["ElapsedTime"].GetLong() ) );

            ProjectOptions = new ProjectOptions( tag["ProjectOptions"] );

            BestMatch = new DNA( tag["BestMatch"] );
            CurrentMatch = BestMatch;

            Initializer = (IInitializer)ModuleManager.ReadModule( tag["Initializer"] );
            Mutator = (IMutator)ModuleManager.ReadModule( tag["Mutator"] );
            Evaluator = (IEvaluator)ModuleManager.ReadModule( tag["Evaluator"] );

            byte[] imageBytes = tag["ImageData"].GetBytes();
            using( MemoryStream ms = new MemoryStream( imageBytes ) ) {
                OriginalImage = new Bitmap( ms );
            }

            var statsTag = (NBTList)tag["MutationStats"];
            foreach( NBTag stat in statsTag ) {
                MutationType mutationType = (MutationType)Enum.Parse( typeof( MutationType ), stat["Type"].GetString() );
                MutationCounts[mutationType] = stat["Count"].GetInt();
                MutationImprovements[mutationType] = stat["Sum"].GetDouble();
            }
        }
예제 #2
0
 /// <summary>
 /// Create a new inmemory db instance and fill it with test data
 /// </summary>
 /// <param name="initializer">initializer to be used for filling initial test data</param>
 /// <returns>In-memory db instance</returns>
 public AppDb CreateTransientDb(IInitializer initializer)
 {
     DbConnection con = Effort.DbConnectionFactory.CreateTransient();
     AppDb db = new AppDb(con);
     initializer.SeedData(db);
     return db;
 }
예제 #3
0
 //readonly Constructor constructor;
 //readonly Destructor destructor;
 //readonly bool isPoolable;
 //readonly IPoolUpdater updater;
 //bool updating;
 protected PoolBase(object reference, IPoolingFactory factory, IPoolingUpdater updater, IInitializer initializer, int startSize)
 {
     this.reference = reference;
     this.factory = factory;
     this.updater = updater;
     this.initializer = initializer;
     //this.startSize = startSize;
 }
예제 #4
0
        /// <summary>
        ///  Build a new cluster based on the provided initializer. <p> Note that for
        ///  building a cluster programmatically, Cluster.NewBuilder provides a slightly less
        ///  verbose shortcut with <link>NewBuilder#Build</link>. </p><p> Also note that that all
        ///  the contact points provided by <c>initializer</c> must share the same
        ///  port.</p>
        /// </summary>
        /// <param name="initializer">the Cluster.Initializer to use</param>
        /// <returns>the newly created Cluster instance </returns>
        public static Cluster BuildFrom(IInitializer initializer)
        {
            if (initializer.ContactPoints.Count == 0)
            {
                throw new ArgumentException("Cannot build a cluster without contact points");
            }

            return new Cluster(initializer.ContactPoints, initializer.GetConfiguration());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LabyrinthEngine" /> class.
 /// </summary>
 /// <param name="renderer">>Object to print.</param>
 /// <param name="userInterface">Interacting with user.</param>
 /// <param name="initializer">Initializing the game.</param>
 /// <param name="player">The player</param>
 /// <param name="grid">The play field</param>
 public LabyrinthEngine(IRenderer renderer, IUserInterface userInterface, IInitializer initializer, IPlayer player, IGrid grid)
     : base(initializer)
 {
     this.renderer = renderer;
     this.userInterface = userInterface;
     this.scoreBoard = new Scoreboard();
     this.player = player;
     this.grid = grid;
     this.gridMemory = new GridMemory();
 }
예제 #6
0
 public static void Initialize(IInitializer initializer)
 {
     initializer.PreInitialize();
     var loggingDelegate = initializer.ConfigureLogging();
     if (loggingDelegate != null)
     {
         Log.SetLogger(loggingDelegate);
     }
     var createDataContexts = initializer.ConfigureDataContexts();
     IoC.Container = initializer.CreateAndConfigureContainer(loggingDelegate,
         createDataContexts);
     initializer.PostInitialize();
 }
예제 #7
0
        public O365ActivityApiWrapper(ILog log, IInitializer initializer, IRetryClient retryClient)
        {
            _log           = log;
            _retryClient   = retryClient;
            _configuration = initializer.Configuration;

            _O365ServiceAuthenticationContract = new ServiceAuthenticationContract
            {
                ClientId     = _configuration.AppSettings.AuditLogClientId,
                ClientSecret = _configuration.AppSettings.AuditLogClientSecret,
                LoginUrl     = _configuration.AppSettings.LoginUrl,
                ResourceUrl  = _configuration.AppSettings.Office365ResourceId,
                TenantId     = _configuration.AppSettings.TenantId
            };
        }
예제 #8
0
 /// <summary>
 /// Turns positive integers (indexes) into dense vectors of fixed size.
 /// </summary>
 /// <param name="input_dim"></param>
 /// <param name="output_dim"></param>
 /// <param name="embeddings_initializer"></param>
 /// <param name="mask_zero"></param>
 /// <returns></returns>
 public Embedding Embedding(int input_dim,
                            int output_dim,
                            IInitializer embeddings_initializer = null,
                            bool mask_zero          = false,
                            TensorShape input_shape = null,
                            int input_length        = -1)
 => new Embedding(new EmbeddingArgs
 {
     InputDim              = input_dim,
     OutputDim             = output_dim,
     MaskZero              = mask_zero,
     InputShape            = input_shape ?? input_length,
     InputLength           = input_length,
     EmbeddingsInitializer = embeddings_initializer
 });
예제 #9
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="filters"></param>
 /// <param name="kernel_size"></param>
 /// <param name="strides"></param>
 /// <param name="padding"></param>
 /// <param name="data_format"></param>
 /// <param name="dilation_rate"></param>
 /// <param name="groups"></param>
 /// <param name="activation">tf.keras.activations</param>
 /// <param name="use_bias"></param>
 /// <param name="kernel_initializer"></param>
 /// <param name="bias_initializer"></param>
 /// <param name="kernel_regularizer"></param>
 /// <param name="bias_regularizer"></param>
 /// <param name="activity_regularizer"></param>
 /// <returns></returns>
 public Conv2D Conv2D(int filters,
                      TensorShape kernel_size   = null,
                      TensorShape strides       = null,
                      string padding            = "valid",
                      string data_format        = null,
                      TensorShape dilation_rate = null,
                      int groups                        = 1,
                      Activation activation             = null,
                      bool use_bias                     = true,
                      IInitializer kernel_initializer   = null,
                      IInitializer bias_initializer     = null,
                      IRegularizer kernel_regularizer   = null,
                      IRegularizer bias_regularizer     = null,
                      IRegularizer activity_regularizer = null)
 => new Conv2D(new Conv2DArgs
예제 #10
0
 public Dense(int units,
              IActivation activation,
              bool use_bias  = true,
              bool trainable = false,
              IInitializer kernel_initializer = null,
              IInitializer bias_initializer   = null) : base(trainable: trainable)
 {
     this.units              = units;
     this.activation         = activation;
     this.use_bias           = use_bias;
     this.kernel_initializer = kernel_initializer;
     this.bias_initializer   = bias_initializer;
     this.supports_masking   = true;
     this.input_spec         = new InputSpec(min_ndim: 2);
 }
예제 #11
0
        private IVariableV1 _true_getter(string name,
                                         TensorShape shape         = null,
                                         TF_DataType dtype         = TF_DataType.TF_FLOAT,
                                         object initializer        = null,
                                         bool?trainable            = null,
                                         List <string> collections = null,
                                         bool validate_shape       = true,
                                         VariableSynchronization synchronization = VariableSynchronization.Auto,
                                         VariableAggregation aggregation         = VariableAggregation.None)
        {
            bool is_scalar = !(shape is null) && shape.ndim == 0;

            if (initializer is IInitializer init)
            {
                return(_get_single_variable(name: name,
                                            shape: shape,
                                            dtype: dtype,
                                            initializer: init,
                                            trainable: trainable,
                                            collections: collections,
                                            validate_shape: validate_shape,
                                            synchronization: synchronization,
                                            aggregation: aggregation));
            }
            else if (initializer is Tensor tensor)
            {
                return(_get_single_variable(name: name,
                                            shape: shape,
                                            dtype: dtype,
                                            initializer: tensor,
                                            trainable: trainable,
                                            validate_shape: validate_shape,
                                            synchronization: synchronization,
                                            aggregation: aggregation));
            }
            else
            {
                IInitializer init1 = null;
                return(_get_single_variable(name: name,
                                            shape: shape,
                                            dtype: dtype,
                                            initializer: init1,
                                            trainable: trainable,
                                            validate_shape: validate_shape,
                                            synchronization: synchronization,
                                            aggregation: aggregation));
            }
        }
예제 #12
0
        public Embedding(EmbeddingArgs args)
            : base(new LayerArgs // copy args
        {
            DType = args.DType,
            Name  = args.Name
        })
        {
            this.args = args;
            if (args.InputShape == null)
            {
                args.InputShape = args.InputLength;
            }

            embeddings_initializer = embeddings_initializer ?? tf.random_uniform_initializer;
            SupportsMasking        = mask_zero;
        }
예제 #13
0
            public InitializerInfo(IInitializableObject owner)
                : base(InitializerInfo.GetHeading(owner), InitializerInfo.GetImageKey(owner))
            {
                if (owner == null)
                {
                    throw new ArgumentNullException();
                }
                if ((owner.Initializer == null) || String.IsNullOrWhiteSpace(owner.Initializer.Source))
                {
                    throw new ArgumentException();
                }

                this.Owner       = owner;
                this.Initializer = owner.Initializer;
                this.SortOrder   = this.Initializer.SortKey;
            }
예제 #14
0
        protected virtual RefVariable add_weight(string name,
                                                 int[] shape,
                                                 TF_DataType dtype        = TF_DataType.DtInvalid,
                                                 IInitializer initializer = null,
                                                 bool?trainable           = null,
                                                 Func <string, int[], TF_DataType, IInitializer, bool, RefVariable> getter = null)
        {
            if (dtype == TF_DataType.DtInvalid)
            {
                dtype = TF_DataType.TF_FLOAT;
            }

            if (trainable == null)
            {
                trainable = true;
            }

            // Initialize variable when no initializer provided
            if (initializer == null)
            {
                // If dtype is DT_FLOAT, provide a uniform unit scaling initializer
                if (dtype.is_floating())
                {
                    initializer = tf.glorot_uniform_initializer;
                }
                else if (dtype.is_integer())
                {
                    initializer = tf.zeros_initializer;
                }
                else
                {
                    throw new ValueError($"An initializer for variable {name} of type {dtype.as_base_dtype()} is required for layer {this.name}");
                }
            }
            var variable = _add_variable_with_custom_getter(name,
                                                            shape,
                                                            dtype: dtype,
                                                            getter: (getter == null) ? base_layer_utils.make_variable : getter,
                                                            overwrite: true,
                                                            initializer: initializer,
                                                            trainable: trainable.Value);

            backend.track_variable(variable);
            _trainable_weights.Add(variable);

            return(variable);
        }
예제 #15
0
            public Tensor conv2d(Tensor inputs,
                                 int filters,
                                 int[] kernel_size,
                                 int[] strides                   = null,
                                 string padding                  = "valid",
                                 string data_format              = "channels_last",
                                 int[] dilation_rate             = null,
                                 bool use_bias                   = true,
                                 Activation activation           = null,
                                 IInitializer kernel_initializer = null,
                                 IInitializer bias_initializer   = null,
                                 bool trainable                  = true,
                                 string name = null)
            {
                if (strides == null)
                {
                    strides = new int[] { 1, 1 }
                }
                ;
                if (dilation_rate == null)
                {
                    dilation_rate = new int[] { 1, 1 }
                }
                ;
                if (bias_initializer == null)
                {
                    bias_initializer = tf.zeros_initializer;
                }

                var layer = new Conv2D(new Conv2DArgs
                {
                    Filters           = filters,
                    KernelSize        = kernel_size,
                    Strides           = strides,
                    Padding           = padding,
                    DataFormat        = data_format,
                    DilationRate      = dilation_rate,
                    Activation        = activation,
                    UseBias           = use_bias,
                    KernelInitializer = kernel_initializer,
                    BiasInitializer   = bias_initializer,
                    Trainable         = trainable,
                    Name = name
                });

                return(layer.Apply(inputs));
            }
예제 #16
0
            public static Tensor conv2d(Tensor inputs,
                                        int filters,
                                        int[] kernel_size,
                                        int[] strides                   = null,
                                        string padding                  = "valid",
                                        string data_format              = "channels_last",
                                        int[] dilation_rate             = null,
                                        bool use_bias                   = true,
                                        IActivation activation          = null,
                                        IInitializer kernel_initializer = null,
                                        IInitializer bias_initializer   = null,
                                        bool trainable                  = true,
                                        string name = null)
            {
                if (strides == null)
                {
                    strides = new int[] { 1, 1 }
                }
                ;
                if (dilation_rate == null)
                {
                    dilation_rate = new int[] { 1, 1 }
                }
                ;
                if (bias_initializer == null)
                {
                    bias_initializer = tf.zeros_initializer;
                }

                var layer = new Conv2D(filters,
                                       kernel_size: kernel_size,
                                       strides: strides,
                                       padding: padding,
                                       data_format: data_format,
                                       dilation_rate: dilation_rate,
                                       activation: activation,
                                       use_bias: use_bias,
                                       kernel_initializer: kernel_initializer,
                                       bias_initializer: bias_initializer,
                                       trainable: trainable,
                                       name: name);

                return(layer.apply(inputs));
            }
        }
    }
예제 #17
0
 public BatchNormalization(int axis       = -1,
                           float momentum = 0.99f,
                           float epsilon  = 0.001f,
                           bool center    = true,
                           bool scale     = true,
                           IInitializer beta_initializer            = null,
                           IInitializer gamma_initializer           = null,
                           IInitializer moving_mean_initializer     = null,
                           IInitializer moving_variance_initializer = null,
                           bool renorm           = false,
                           float renorm_momentum = 0.99f,
                           bool trainable        = true,
                           string name           = null) : base(trainable: trainable,
                                                                name: name)
 {
     this.axis     = new int[] { axis };
     this.momentum = momentum;
     this.epsilon  = epsilon;
     this.center   = center;
     this.scale    = scale;
     if (beta_initializer == null)
     {
         beta_initializer = tf.zeros_initializer;
     }
     if (gamma_initializer == null)
     {
         gamma_initializer = tf.ones_initializer;
     }
     if (moving_mean_initializer == null)
     {
         moving_mean_initializer = tf.zeros_initializer;
     }
     if (moving_variance_initializer == null)
     {
         moving_variance_initializer = tf.ones_initializer;
     }
     this.beta_initializer            = beta_initializer;
     this.gamma_initializer           = gamma_initializer;
     this.moving_mean_initializer     = moving_mean_initializer;
     this.moving_variance_initializer = moving_variance_initializer;
     this.renorm           = renorm;
     this.fused            = true;
     this.supports_masking = true;
     this._bessels_correction_test_only = true;
 }
        public static RefVariable get_variable(string name,
                                               TensorShape shape        = null,
                                               TF_DataType dtype        = TF_DataType.DtInvalid,
                                               IInitializer initializer = null,
                                               bool?trainable           = null,
                                               VariableSynchronization synchronization = VariableSynchronization.AUTO,
                                               VariableAggregation aggregation         = VariableAggregation.NONE)
        {
            var scope = Tensorflow.variable_scope.get_variable_scope();
            var store = Tensorflow.variable_scope._get_default_variable_store();

            return(scope.get_variable(store,
                                      name,
                                      shape: shape,
                                      dtype: dtype,
                                      initializer: initializer,
                                      trainable: trainable));
        }
예제 #19
0
        protected virtual void add_weight(string name,
                                          int[] shape,
                                          TF_DataType dtype        = TF_DataType.DtInvalid,
                                          IInitializer initializer = null,
                                          bool?trainable           = null,
                                          Func <string, int[], TF_DataType, IInitializer, bool, RefVariable> getter = null)
        {
            var variable = _add_variable_with_custom_getter(name,
                                                            shape,
                                                            dtype: dtype,
                                                            getter: getter,
                                                            overwrite: true,
                                                            initializer: initializer,
                                                            trainable: trainable.Value);

            backend.track_variable(variable);
            _trainable_weights.Add(variable);
        }
예제 #20
0
 internal DuplicationKeyRule(
     IContext context,
     ISafeMetadataProvider <TEntity> safeMetadataProvider,
     IMetadataParser <TEntity> metadataParser,
     ICache <TEntity> cache,
     IInitializer initializer)
 {
     this.safeMetadataProvider = safeMetadataProvider;
     this.metadataParser       = metadataParser;
     this.cache   = cache;
     this.indices = new IndexWrapper[0];
     if (this.IsEntityTypeSupported(context))
     {
         initializer.Register(
             new Initializer(this),
             message: Resources.IndexingCache);
     }
 }
예제 #21
0
        /// <summary>
        /// Adds a new variable to the layer.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="shape"></param>
        /// <param name="dtype"></param>
        /// <param name="initializer"></param>
        /// <param name="trainable"></param>
        /// <returns></returns>
        public static RefVariable make_variable(string name,
                                                int[] shape,
                                                TF_DataType dtype        = TF_DataType.TF_FLOAT,
                                                IInitializer initializer = null,
                                                bool trainable           = true,
                                                bool use_resource        = true)
        {
            var initializing_from_value = false;

            ops.init_scope();

            Func <Tensor> init_val = () => initializer.call(new TensorShape(shape), dtype: dtype);

            var variable_dtype = dtype.as_base_dtype();
            var v = tf.Variable(init_val);

            return(v);
        }
예제 #22
0
 public MappingRepository(
     IContext context,
     IOperationExecutive operationExecutive,
     IMappingDataRepository mappingDataRepository,
     ISafeRepository safeRepository,
     IHashingSerializer <TEntity> hashingSerializer,
     IEventDispatcher <TEntity> eventDispatcher,
     IInitializer initializer)
 {
     this.context               = context;
     this.operationExecutive    = operationExecutive;
     this.mappingDataRepository = mappingDataRepository;
     this.safeRepository        = safeRepository;
     this.hashingSerializer     = hashingSerializer;
     initializer.Register(
         this.mappingDataRepository.CreateInitializer(eventDispatcher),
         suppressEvents: true);
 }
예제 #23
0
 public Embedding(int input_dim, int output_dim,
                  IInitializer embeddings_initializer = null,
                  bool mask_zero    = false,
                  TF_DataType dtype = TF_DataType.TF_FLOAT,
                  int[] input_shape = null,
                  int input_length  = -1) :
     base(new LayerArgs
 {
     DType      = dtype,
     InputShape = input_shape ?? new[] { input_length }
 })
 {
     this.input_dim              = input_dim;
     this.output_dim             = output_dim;
     this.embeddings_initializer = embeddings_initializer == null ? tf.uniform_initializer : embeddings_initializer;
     this.mask_zero              = mask_zero;
     SupportsMasking             = mask_zero;
     this.input_length           = input_length;
 }
예제 #24
0
        /// <summary>
        /// Restore-on-create for a variable be saved with this `Checkpointable`.
        /// </summary>
        /// <returns></returns>
        protected virtual IVariableV1 _add_variable_with_custom_getter(string name,
                                                                       int[] shape,
                                                                       TF_DataType dtype        = TF_DataType.TF_FLOAT,
                                                                       IInitializer initializer = null,
                                                                       Func <string, int[], TF_DataType, IInitializer, bool, IVariableV1> getter = null,
                                                                       bool overwrite    = false,
                                                                       bool trainable    = false,
                                                                       bool use_resource = false,
                                                                       VariableSynchronization synchronization = VariableSynchronization.Auto,
                                                                       VariableAggregation aggregation         = VariableAggregation.None)
        {
            ops.init_scope();
#pragma warning disable CS0219 // Variable is assigned but its value is never used
            IInitializer checkpoint_initializer = null;
#pragma warning restore CS0219 // Variable is assigned but its value is never used
            if (tf.context.executing_eagerly())
#pragma warning disable CS0642 // Possible mistaken empty statement
            {
                ;
            }
#pragma warning restore CS0642 // Possible mistaken empty statement
            else
            {
                checkpoint_initializer = null;
            }

            IVariableV1 new_variable;
            new_variable = getter(name, shape, dtype, initializer, trainable);

            // If we set an initializer and the variable processed it, tracking will not
            // assign again. It will add this variable to our dependencies, and if there
            // is a non-trivial restoration queued, it will handle that. This also
            // handles slot variables.
            if (!overwrite || new_variable is RefVariable)
            {
                return(_track_checkpointable(new_variable, name: name,
                                             overwrite: overwrite));
            }
            else
            {
                return(new_variable);
            }
        }
예제 #25
0
        public void InitLengths(IInitializer cacher)
        {
            int i = index_lo;

            Array.Resize(ref lengths, index_hi + 1);
            int prev_length = 0, new_length = 0;

            while (i < index_hi)
            {
                new_length = cacher.SetGetTime(this, i);
                if (new_length < 0)
                {
                    new_length = int.MaxValue;
                }
                lengths[++i] = new_length;

                prev_length = new_length;
            }
        }
        public CassandraProvider(IConfiguration configuration, IKeyspaceNamingStrategy keyspaceNamingStrategy, ICassandraReplicationStrategy replicationStrategy, IInitializer initializer = null)
        {
            if (configuration is null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (keyspaceNamingStrategy is null)
            {
                throw new ArgumentNullException(nameof(keyspaceNamingStrategy));
            }
            if (replicationStrategy is null)
            {
                throw new ArgumentNullException(nameof(replicationStrategy));
            }

            this.configuration          = configuration;
            this.keyspaceNamingStrategy = keyspaceNamingStrategy;
            this.replicationStrategy    = replicationStrategy;
            this.initializer            = initializer;
        }
        private RefVariable _true_getter(string name,
                                         TensorShape shape        = null,
                                         TF_DataType dtype        = TF_DataType.TF_FLOAT,
                                         IInitializer initializer = null,
                                         bool?trainable           = null,
                                         bool validate_shape      = true,
                                         VariableSynchronization synchronization = VariableSynchronization.AUTO,
                                         VariableAggregation aggregation         = VariableAggregation.NONE)
        {
            bool is_scalar = shape.NDim == 0;

            return(_get_single_variable(name: name,
                                        shape: shape,
                                        dtype: dtype,
                                        initializer: initializer,
                                        trainable: trainable,
                                        validate_shape: validate_shape,
                                        synchronization: synchronization,
                                        aggregation: aggregation));
        }
예제 #28
0
 public KMeans(Tensor inputs,
               int num_clusters,
               IInitializer initial_clusters      = null,
               string distance_metric             = SQUARED_EUCLIDEAN_DISTANCE,
               bool use_mini_batch                = false,
               int mini_batch_steps_per_iteration = 1,
               int random_seed = 0,
               int kmeans_plus_plus_num_retries = 2,
               int kmc2_chain_length            = 200)
 {
     _inputs           = new Tensor[] { inputs };
     _num_clusters     = num_clusters;
     _initial_clusters = initial_clusters;
     _distance_metric  = distance_metric;
     _use_mini_batch   = use_mini_batch;
     _mini_batch_steps_per_iteration = mini_batch_steps_per_iteration;
     _random_seed = random_seed;
     _kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries;
     _kmc2_chain_length            = kmc2_chain_length;
 }
예제 #29
0
        /// <summary>
        /// Restore-on-create for a variable be saved with this `Checkpointable`.
        /// </summary>
        /// <returns></returns>
        protected virtual RefVariable _add_variable_with_custom_getter(string name,
                                                                       int[] shape,
                                                                       TF_DataType dtype        = TF_DataType.TF_FLOAT,
                                                                       IInitializer initializer = null,
                                                                       Func <string, int[], TF_DataType, IInitializer, bool, RefVariable> getter = null,
                                                                       bool overwrite = false,
                                                                       bool trainable = false)
        {
            var new_variable = getter(name, shape, dtype, initializer, trainable);

            if (!overwrite || new_variable is RefVariable)
            {
                return(_track_checkpointable(new_variable, name: name,
                                             overwrite: overwrite));
            }
            else
            {
                return(new_variable);
            }
        }
예제 #30
0
 public GarbageCollectionSegmentRunner(
     IContext context,
     IParameterProvider parameterProvider,
     IOperationExecutive operationExecutive,
     IGateway <TEntity> gateway,
     ISafeRepository safeRepository,
     IEventDispatcher <TEntity> eventDispatcher,
     IInitializer initializer)
 {
     this.context               = context;
     this.parameterProvider     = parameterProvider;
     this.operationExecutive    = operationExecutive;
     this.gateway               = gateway;
     this.safeRepository        = safeRepository;
     this.eventDispatcher       = eventDispatcher;
     this.idsOfEntitiesToDelete = null;
     initializer.Register(
         new Initializer(this),
         suppressEvents: true);
 }
예제 #31
0
        public VdCnn(int alphabet_size, int document_max_len, int num_class)
        {
            embedding_size  = 16;
            filter_sizes    = new int[] { 3, 3, 3, 3, 3 };
            num_filters     = new int[] { 64, 64, 128, 256, 512 };
            num_blocks      = new int[] { 2, 2, 2, 2 };
            learning_rate   = 0.001f;
            cnn_initializer = tf.keras.initializers.he_normal();
            x           = tf.placeholder(tf.int32, new TensorShape(-1, document_max_len), name: "x");
            y           = tf.placeholder(tf.int32, new TensorShape(-1), name: "y");
            is_training = tf.placeholder(tf.boolean, new TensorShape(), name: "is_training");
            global_step = tf.Variable(0, trainable: false);

            // Embedding Layer
            with(tf.name_scope("embedding"), delegate
            {
                var init_embeddings = tf.random_uniform(new int[] { alphabet_size, embedding_size }, -1.0f, 1.0f);
                embeddings          = tf.get_variable("embeddings", initializer: init_embeddings);
                x_emb      = tf.nn.embedding_lookup(embeddings, x);
                x_expanded = tf.expand_dims(x_emb, -1);
            });

            Tensor conv0 = null;
            Tensor conv1 = null;

            // First Convolution Layer
            with(tf.variable_scope("conv-0"), delegate
            {
                conv0 = tf.layers.conv2d(x_expanded,
                                         filters: num_filters[0],
                                         kernel_size: new int[] { filter_sizes[0], embedding_size },
                                         kernel_initializer: cnn_initializer,
                                         activation: tf.nn.relu);

                conv0 = tf.transpose(conv0, new int[] { 0, 1, 3, 2 });
            });

            with(tf.name_scope("conv-block-1"), delegate {
                conv1 = conv_block(conv0, 1);
            });
        }
예제 #32
0
        public LanguageProvider(ILogger logger,
                                IInitializer initializeService,
                                SidekickSettings settings)
        {
            this.logger            = logger.ForContext(GetType());
            this.initializeService = initializeService;
            this.settings          = settings;

            AvailableLanguages = new List <LanguageAttribute>();
            foreach (var type in typeof(LanguageAttribute).GetImplementedAttribute())
            {
                var attribute = type.GetAttribute <LanguageAttribute>();
                attribute.ImplementationType = type;
                AvailableLanguages.Add(attribute);
            }

            if (!SetLanguage(settings.Language_Parser))
            {
                SetLanguage(DefaultLanguage);
            }
        }
예제 #33
0
            public static Tensor dense(Tensor inputs,
                                       int units,
                                       IActivation activation          = null,
                                       bool use_bias                   = true,
                                       IInitializer kernel_initializer = null,
                                       IInitializer bias_initializer   = null,
                                       bool trainable                  = true,
                                       string name = null,
                                       bool?reuse  = null)
            {
                if (bias_initializer == null)
                {
                    bias_initializer = tf.zeros_initializer;
                }

                var layer = new Dense(units, activation,
                                      use_bias: use_bias,
                                      kernel_initializer: kernel_initializer);

                return(layer.apply(inputs));
            }
예제 #34
0
        public CassandraProvider(IOptionsMonitor <CassandraProviderOptions> optionsMonitor, IKeyspaceNamingStrategy keyspaceNamingStrategy, ICassandraReplicationStrategy replicationStrategy, ILogger <CassandraProvider> logger, IInitializer initializer = null)
        {
            if (optionsMonitor is null)
            {
                throw new ArgumentNullException(nameof(optionsMonitor));
            }
            if (keyspaceNamingStrategy is null)
            {
                throw new ArgumentNullException(nameof(keyspaceNamingStrategy));
            }
            if (replicationStrategy is null)
            {
                throw new ArgumentNullException(nameof(replicationStrategy));
            }

            this.options = optionsMonitor.CurrentValue;
            this.keyspaceNamingStrategy = keyspaceNamingStrategy;
            this.replicationStrategy    = replicationStrategy;
            this.initializer            = initializer;
            this.logger = logger;
        }
        public RefVariable get_variable(string name,
                                        TensorShape shape        = null,
                                        TF_DataType dtype        = TF_DataType.TF_FLOAT,
                                        IInitializer initializer = null,
                                        bool?trainable           = null,
                                        bool validate_shape      = true,
                                        VariableSynchronization synchronization = VariableSynchronization.AUTO,
                                        VariableAggregation aggregation         = VariableAggregation.NONE)
        {
            dtype     = dtype.as_base_dtype();
            trainable = variable_scope._get_trainable_value(synchronization, trainable);

            return(_true_getter(name,
                                shape: shape,
                                dtype: dtype,
                                initializer: initializer,
                                trainable: trainable,
                                validate_shape: validate_shape,
                                synchronization: synchronization,
                                aggregation: aggregation));
        }
예제 #36
0
        /// <summary>
        /// Helper function for creating a slot variable.
        /// </summary>
        /// <param name="primary"></param>
        /// <param name="val"></param>
        /// <param name="scope"></param>
        /// <param name="validate_shape"></param>
        /// <param name="shape"></param>
        /// <param name="dtype"></param>
        /// <returns></returns>
        private RefVariable _create_slot_var(VariableV1 primary, IInitializer val, string scope, bool validate_shape,
                                             TensorShape shape, TF_DataType dtype)
        {
            bool use_resource = primary is ResourceVariable;

            if (resource_variable_ops.is_resource_variable(primary))
            {
                use_resource = true;
            }

            var slot = tf.get_variable(
                scope,
                initializer: val,
                trainable: false,
                use_resource: use_resource,
                shape: shape,
                dtype: dtype,
                validate_shape: validate_shape);

            return(slot);
        }
		/// <summary>Initializes the specified is for simulator.</summary>
		/// <param name="isForSimulator" >
		///     if set to <c>true</c> [is for simulator].
		/// </param>
		public InitializeModules Initialize(bool isForSimulator = false)
		{
			this.IsForSimulator = isForSimulator;

			if (this.IsForSimulator)
			{
				this.simulatorInitializer = this.Initializers.FirstOrDefault(foo => foo.ModuleSerie_Key == typeof (InitializerSimulator).ToString());
				if (this.simulatorInitializer == null)
				{
					this.ErrorTracking.Add(ErrorIdList.InitilizeModule_NoSimulatorInitializer, ErrorGravity.FatalApplication);
					return null;
				}
				// Load config module settings. 
				this.Modules = this.LoadModuleSetting.LoadConfig(this.InitialiseModuleSimulator);
			}
			else
			{
				// Load config module settings. 
				this.Modules = this.LoadModuleSetting.LoadConfig(this.InitialiseModuleProductive);
			}
			return this;
		}
예제 #38
0
파일: Item.cs 프로젝트: BjkGkh/R106
        internal Item(uint Id, int Sprite, string PublicName, string Name, string Type, int Width, int Length, 
            double Height, bool Stackable, bool Walkable, bool IsSeat, bool AllowRecycle, bool AllowTrade, bool AllowMarketplaceSell, bool AllowGift, bool AllowInventoryStack,
            InteractionType InteractionType, int Modes, string VendingIds, SortedDictionary<uint, double> heightModes, bool isGroupItem)
        {
            this.Id = Id;
            this.SpriteId = Sprite;
            this.PublicName = PublicName;
            this.Name = Name;
			this.Type = char.ToLower(Type[0]);
            this.Width = Width;
            this.Length = Length;
            this.Height = Height;
            this.Stackable = Stackable;
            this.Walkable = Walkable;
            this.IsSeat = IsSeat;
            this.AllowRecycle = AllowRecycle;
			this.HeightModes = heightModes;
            this.AllowTrade = AllowTrade;
            this.AllowMarketplaceSell = AllowMarketplaceSell;
            this.AllowGift = AllowGift;
            this.AllowInventoryStack = AllowInventoryStack;
            this.InteractionType = InteractionType;
            this.FurniInteractor = FurniInteractorFactory.GetInteractable(this.InteractionType);
            this.FurniInitializer = FurniIInitializerFactory.GetInteractable(this.InteractionType);
            this.FurniTrigger = FurniTriggerFactory.GetInteractable(this.InteractionType);
            this.Modes = Modes;
            this.VendingIds = new List<int>();
            this.IsGift = false;
            this.IsGroupItem = isGroupItem;

            if (VendingIds.Contains(","))
            {
                foreach (string VendingId in VendingIds.Split(','))
                    this.VendingIds.Add(TextHandling.ParseInt32(VendingId));
            }
            else if (!VendingIds.Equals(string.Empty) && (TextHandling.ParseInt32(VendingIds)) > 0)
                this.VendingIds.Add(TextHandling.ParseInt32(VendingIds));
        }
예제 #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Engine" /> class.
 /// </summary>
 /// <param name="initializer">Game initializer</param>
 protected Engine(IInitializer initializer)
 {
     this.Initializer = initializer;
 }
예제 #40
0
        /// <summary>
        ///  Build a new cluster based on the provided initializer. <p> Note that for
        ///  building a cluster programmatically, Cluster.NewBuilder provides a slightly less
        ///  verbose shortcut with <link>NewBuilder#Build</link>. </p><p> Also note that that all
        ///  the contact points provided by <code>* initializer</code> must share the same
        ///  port.</p>
        /// </summary>
        /// <param name="initializer"> the Cluster.Initializer to use </param>
        /// 
        /// <returns>the newly created Cluster instance </returns>
        public static Cluster BuildFrom(IInitializer initializer)
        {
            ICollection<IPAddress> contactPoints = initializer.ContactPoints;
            if (contactPoints.Count == 0)
                throw new ArgumentException("Cannot build a cluster without contact points");

            return new Cluster(contactPoints, initializer.GetConfiguration());
        }
예제 #41
0
        /// <summary>
        ///  Build a new cluster based on the provided initializer. <p> Note that for
        ///  building a cluster programmatically, Cluster.NewBuilder provides a slightly less
        ///  verbose shortcut with <link>NewBuilder#Build</link>. </p><p> Also note that that all
        ///  the contact points provided by <code>* initializer</code> must share the same
        ///  port.</p>
        /// </summary>
        /// <param name="initializer"> the Cluster.Initializer to use </param>
        /// 
        /// <returns>the newly created Cluster instance </returns>
        public static Cluster BuildFrom(IInitializer initializer)
        {
            IEnumerable<IPAddress> contactPoints = initializer.ContactPoints;
            //if (contactPoints.)
            //    throw new IllegalArgumentException("Cannot build a cluster without contact points");

            return new Cluster(contactPoints, initializer.GetConfiguration());
        }
 public InitializeOperation(object reference, IInitializer initializer)
 {
     this.reference = reference;
     this.initializer = initializer;
 }