Esempio n. 1
0
        public override void AddField(ScriptField field)
        {
            Variable value = Initializers[field.TypeName](field.Access, field.Usage, field.Alias, InnerScope, field.ScriptTrace);

            value.InvokeOperation(Operation.Set, Compiler.ParseValue(field.Init, field.Scope), field.ScriptTrace);
            Fields.Add(value.ObjectName, value);
        }
        private void MergeBehaviorOverrides(DictionaryAdapterMeta meta)
        {
            if (Descriptor == null)
            {
                return;
            }

            var typeDescriptor = Descriptor as DictionaryDescriptor;

            if (typeDescriptor != null)
            {
                Initializers = Initializers.Prioritize(typeDescriptor.Initializers).ToArray();
            }

            Properties = new Dictionary <string, PropertyDescriptor>();

            foreach (var property in meta.Properties)
            {
                var propertyDescriptor = property.Value;

                var propertyOverride = new PropertyDescriptor(propertyDescriptor, false)
                                       .AddKeyBuilders(propertyDescriptor.KeyBuilders.Prioritize(Descriptor.KeyBuilders))
                                       .AddGetters(propertyDescriptor.Getters.Prioritize(Descriptor.Getters))
                                       .AddSetters(propertyDescriptor.Setters.Prioritize(Descriptor.Setters));

                Properties.Add(property.Key, propertyOverride);
            }
        }
        static Model CreateModel(Function inputVariable, Variable targetVariable, int targetCount,
                                 DataType dataType, DeviceDescriptor device)
        {
            var random = new Random(232);
            Func <CNTKDictionary> weightInit = () => Initializers.GlorotNormal(random.Next());
            var biasInit = Initializers.Zero();

            // Create the architecture.
            var network = inputVariable

                          .Dense(32, weightInit(), biasInit, device, dataType)
                          .ReLU()
                          .Dense(32, weightInit(), biasInit, device, dataType)
                          .ReLU()
                          .Dense(targetCount, weightInit(), biasInit, device, dataType);

            // loss
            var lossFunc   = Losses.MeanSquaredError(network.Output, targetVariable);
            var metricFunc = Losses.MeanAbsoluteError(network.Output, targetVariable);

            // setup trainer.
            var learner = CntkCatalyst.Learners.Adam(network.Parameters());
            var trainer = CNTKLib.CreateTrainer(network, lossFunc, metricFunc, new LearnerVector {
                learner
            });

            var model = new Model(trainer, network, dataType, device);

            Trace.WriteLine(model.Summary());
            return(model);
        }
        //private void Flush(UInt64 start, UInt64 length) {
        //	VkMappedMemoryRange memoryRange = VkMappedMemoryRange.New();
        //	memoryRange.memory = vkMemory;
        //	memoryRange.size = length;
        //	memoryRange.offset = start;

        //	Util.CheckResult(vkFlushMappedMemoryRanges(device.device, 1, ref memoryRange));
        //}


        private void Allocate()
        {
            if (usageHint == BufferMemoryUsageHint.Static)
            {
                bufferUsageFlags |= VkBufferUsageFlags.TransferDst;
            }

            // Create the buffer handle
            VkBufferCreateInfo bufferCreateInfo = Initializers.bufferCreateInfo(bufferUsageFlags, size);

            bufferCreateInfo.sharingMode = VkSharingMode.Exclusive;
            Util.CheckResult(vkCreateBuffer(device.device, &bufferCreateInfo, null, out vkBuffer));

            // Create the memory backing up the buffer handle
            VkMemoryRequirements memReqs;

            vkGetBufferMemoryRequirements(device.device, vkBuffer, &memReqs);

            var hostVisible = usageHint == BufferMemoryUsageHint.Dynamic;

            memory = device.memoryAllocator.Allocate(memReqs, hostVisible);

            // Attach the memory to the buffer object
            Util.CheckResult(vkBindBufferMemory(device.device, vkBuffer, memory.vkDeviceMemory, memory.offset));
        }
Esempio n. 5
0
        /// <summary>
        /// Builds the RNN.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="hiddenSize">Size of the hidden.</param>
        /// <param name="numLayers">The number layers.</param>
        /// <param name="bidirectional">if set to <c>true</c> [bidirectional].</param>
        /// <param name="weightInitializer">The weight initializer.</param>
        /// <param name="rnnName">Name of the RNN.</param>
        /// <returns></returns>
        private static Function BuildRNN(Variable input, int dim, uint hiddenSize, uint numLayers, bool bidirectional = false, string weightInitializer = OptInitializers.Xavier, string rnnName = "")
        {
            int[] s = input.Shape.Dimensions.ToArray();
            var weights = new Parameter(s, DataType.Float, Initializers.Get(weightInitializer), GlobalParameters.Device);

            return CNTKLib.OptimizedRNNStack(Variable.InputVariable(s, DataType.Float), weights, hiddenSize, numLayers, bidirectional, rnnName);
        }
Esempio n. 6
0
        /// <summary>
        /// 2D convolution layer (e.g. spatial convolution over images). This layer creates a convolution kernel that is convolved with the layer input to produce a tensor of outputs. If  use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well.
        /// </summary>
        /// <param name="layer">The output of the last layer.</param>
        /// <param name="channels">Integer, the dimensionality of the output space.</param>
        /// <param name="kernalSize">A tuple of 2 integers, specifying the width and height of the 2D convolution window. Can be a single integer to specify the same value for all spatial dimensions.</param>
        /// <param name="strides">A tuple of 2 integers, specifying the strides of the convolution along the width and height. Can be a single integer to specify the same value for all spatial dimensions. Specifying any stride value != 1 is incompatible with specifying any dilation_rate value != 1.</param>
        /// <param name="padding">Boolean, if true results in padding the input such that the output has the same length as the original input.</param>
        /// <param name="dialation">A tuple of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1.</param>
        /// <param name="activation">Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). <see cref="SiaNet.Common.OptActivations"/></param>
        /// <param name="useBias">Boolean, whether the layer uses a bias vector.</param>
        /// <param name="weightInitializer">Initializer for the kernel weights matrix. <see cref="SiaNet.Common.OptInitializers"/></param>
        /// <param name="biasInitializer">Initializer for the bias vector. <see cref="SiaNet.Common.OptInitializers"/></param>
        /// <returns></returns>
        public static Function Conv2D(Variable layer, int channels, Tuple<int, int> kernalSize, Tuple<int, int> strides = null, bool padding = true, Tuple<int, int> dialation = null, string activation = OptActivations.None, bool useBias = false, string weightInitializer = OptInitializers.Xavier, string biasInitializer = OptInitializers.Zeros)
        {
            int numInputChannels = layer.Shape[layer.Shape.Rank - 1];
            var convParams = new Parameter(new int[] { kernalSize.Item1, kernalSize.Item2, numInputChannels, channels }, DataType.Float, Initializers.Get(weightInitializer), GlobalParameters.Device);
            if (dialation == null)
            {
                dialation = new Tuple<int, int>(1, 1);
            }

            int[] stridesParams = null;
            if(strides!=null)
            {
                stridesParams = new int[] { strides.Item1, strides.Item2 };
            }

            var conv = CNTKLib.Convolution(convParams, layer, stridesParams, new BoolVector(new bool[] { true, true }), new BoolVector(new bool[] { padding, padding, false }), new int[] { dialation.Item1, dialation.Item2 });

            Parameter bias = null;
            if (useBias)
            {
                bias = new Parameter(conv.Output.Shape, DataType.Float, Initializers.Get(biasInitializer), GlobalParameters.Device);
                conv = CNTKLib.Plus(bias, conv);
            }

            return Basic.Activation(conv, activation);
        }
Esempio n. 7
0
        /// <summary>
        /// Begin a renderpass without clearing color or depth.
        /// </summary>
        public void BeginRenderPass(RenderPass renderPass, FrameBuffer frameBuffer, bool useSecondaryCommandBuffers)
        {
            CheckBegun();
            CheckNotInRenderPass();
            //FixedArray2<VkClearValue> clearValues = new FixedArray2<VkClearValue>();
            //clearValues.First.color = new VkClearColorValue(0, 0, 0);
            //clearValues.Second.depthStencil = new VkClearDepthStencilValue() { depth = 1.0f, stencil = 0 };

            VkRenderPassBeginInfo renderPassBeginInfo = Initializers.renderPassBeginInfo();

            renderPassBeginInfo.renderPass               = renderPass.vkRenderPass;
            renderPassBeginInfo.renderArea.offset.x      = 0;
            renderPassBeginInfo.renderArea.offset.y      = 0;
            renderPassBeginInfo.renderArea.extent.width  = frameBuffer.swapchain.width;
            renderPassBeginInfo.renderArea.extent.height = frameBuffer.swapchain.height;
            //renderPassBeginInfo.clearValueCount = 2;
            //renderPassBeginInfo.pClearValues = &clearValues.First;
            renderPassBeginInfo.framebuffer = frameBuffer.vkFrameBuffer;

            renderPassUseSecondaryBuffers = useSecondaryCommandBuffers;
            VkSubpassContents subPassContents = useSecondaryCommandBuffers
                                ? VkSubpassContents.SecondaryCommandBuffers
                                : VkSubpassContents.Inline;

            vkCmdBeginRenderPass(vkCmd, &renderPassBeginInfo, subPassContents);

            VkViewport viewport = Initializers.viewport((float)frameBuffer.swapchain.width, (float)frameBuffer.swapchain.height, 0.0f, 1.0f);

            vkCmdSetViewport(vkCmd, 0, 1, &viewport);

            VkRect2D scissor = Initializers.rect2D(frameBuffer.swapchain.width, frameBuffer.swapchain.height, 0, 0);

            vkCmdSetScissor(vkCmd, 0, 1, &scissor);
            inRenderPass = true;
        }
Esempio n. 8
0
        public void Dense_InputRank_And_MapRank_At_The_Same_Time_Throws()
        {
            var inputVariable = CNTKLib.InputVariable(new int[] { 2 }, m_dataType);

            Layers.Dense(inputVariable, 2, Initializers.GlorotUniform(seed: 232), Initializers.Zero(),
                         m_device, m_dataType, inputRank: 1, mapRank: 1);
        }
Esempio n. 9
0
        public void Model_Use_Case()
        {
            var inputShape      = new int[] { 28, 28, 1 };
            var numberOfClasses = 10;
            var outputShape     = new int[] { numberOfClasses };

            (var observations, var targets) = CreateArtificialData(inputShape, outputShape, observationCount: 100);

            var dataType = DataType.Float;
            var device   = DeviceDescriptor.UseDefaultDevice();

            var random = new Random(232);
            Func <CNTKDictionary> weightInit = () => Initializers.GlorotNormal(random.Next());
            var biasInit = Initializers.Zero();

            // Create the architecture.
            var network = Layers.Input(inputShape, dataType)
                          .Dense(512, weightInit(), biasInit, device, dataType)
                          .ReLU()
                          .Dense(numberOfClasses, weightInit(), biasInit, device, dataType)
                          .Softmax();

            // setup input and target variables.
            var inputVariable  = network.Arguments[0];
            var targetVariable = Variable.InputVariable(network.Output.Shape, dataType);

            // loss
            var lossFunc   = Losses.CategoricalCrossEntropy(network.Output, targetVariable);
            var metricFunc = Metrics.Accuracy(network.Output, targetVariable);

            // setup trainer.
            var learner = Learners.MomentumSGD(network.Parameters());
            var trainer = CNTKLib.CreateTrainer(network, lossFunc, metricFunc, new LearnerVector {
                learner
            });

            var model = new Model(trainer, network, dataType, device);

            // setup name to data.
            var nameToData = new Dictionary <string, MemoryMinibatchData>
            {
                { "observations", observations },
                { "targets", targets }
            };

            // setup name to variable
            var nameToVariable = new Dictionary <string, Variable>
            {
                { "observations", inputVariable },
                { "targets", targetVariable },
            };

            var trainSource = new MemoryMinibatchSource(nameToVariable, nameToData, seed: 232, randomize: true);

            model.Fit(trainSource, batchSize: 8, epochs: 2);

            (var loss, var metric) = model.Evaluate(trainSource);

            Trace.WriteLine($"Final evaluation - Loss: {loss}, Metric: {metric}");
        }
Esempio n. 10
0
        public void BeginAndContinueRenderPass(RenderContext context)
        {
            if (vkCmd.Handle == NullHandle)
            {
                return;
            }
            CheckNotBegun();
            CheckSecondary();

            VkCommandBufferBeginInfo       cmdBufInfo      = Initializers.commandBufferBeginInfo();
            VkCommandBufferInheritanceInfo inheritanceInfo = VkCommandBufferInheritanceInfo.New();

            cmdBufInfo.flags = VkCommandBufferUsageFlags.RenderPassContinue;

            inheritanceInfo.renderPass  = context.currentRenderPass.vkRenderPass;
            inheritanceInfo.subpass     = context.currentSubPassIndex;
            inheritanceInfo.framebuffer = context.currentFrameBuffer.vkFrameBuffer;

            cmdBufInfo.pInheritanceInfo = &inheritanceInfo;

            Util.CheckResult(vkBeginCommandBuffer(vkCmd, &cmdBufInfo));
            begun        = true;
            inRenderPass = true;

            //Does not draw anything without viewport and scissor
            SetViewportScissor(context);
        }
Esempio n. 11
0
        void SetupDescriptorSet(Pipeline pipeline, GraphicsDevice device, UniformBuffer uniformBuffer, Texture2D texture_colorMap)
        {
            var dsl = pipeline.descriptorSetLayout;
            VkDescriptorSetAllocateInfo allocInfo =
                Initializers.descriptorSetAllocateInfo(
                    pipeline.descriptorPool,
                    &dsl,
                    1);

            Util.CheckResult(vkAllocateDescriptorSets(device.device, &allocInfo, out pipeline.descriptorSet));

            VkDescriptorImageInfo texDescriptor =
                Initializers.descriptorImageInfo(
                    texture_colorMap.sampler,
                    texture_colorMap.view,
                    VkImageLayout.General);

            VkDescriptorBufferInfo temp = uniformBuffer.GetVkDescriptor();

            FixedArray2 <VkWriteDescriptorSet> writeDescriptorSets = new FixedArray2 <VkWriteDescriptorSet>(
                // Binding 0 : Vertex shader uniform buffer
                Initializers.writeDescriptorSet(
                    pipeline.descriptorSet,
                    VkDescriptorType.UniformBuffer,
                    uniformBuffer.location,
                    &temp),
                // Binding 1 : Color map
                Initializers.writeDescriptorSet(
                    pipeline.descriptorSet,
                    VkDescriptorType.CombinedImageSampler,
                    1,
                    &texDescriptor));

            vkUpdateDescriptorSets(device.device, (writeDescriptorSets.Count), ref writeDescriptorSets.First, 0, null);
        }
Esempio n. 12
0
        void SetupDescriptorSetLayout(Pipeline pipeline, GraphicsDevice device)
        {
            FixedArray2 <VkDescriptorSetLayoutBinding> setLayoutBindings = new FixedArray2 <VkDescriptorSetLayoutBinding>(
                // Binding 0 : Vertex shader uniform buffer
                Initializers.descriptorSetLayoutBinding(
                    VkDescriptorType.UniformBuffer,
                    VkShaderStageFlags.Vertex | VkShaderStageFlags.Fragment,
                    0),
                // Binding 1 : Fragment shader combined sampler
                Initializers.descriptorSetLayoutBinding(
                    VkDescriptorType.CombinedImageSampler,
                    VkShaderStageFlags.Fragment,
                    1));

            VkDescriptorSetLayoutCreateInfo descriptorLayout =
                Initializers.descriptorSetLayoutCreateInfo(
                    &setLayoutBindings.First,
                    setLayoutBindings.Count);

            Util.CheckResult(vkCreateDescriptorSetLayout(device.device, &descriptorLayout, null, out pipeline.descriptorSetLayout));

            var dsl = pipeline.descriptorSetLayout;
            VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo =
                Initializers.pipelineLayoutCreateInfo(
                    &dsl,
                    1);

            Util.CheckResult(vkCreatePipelineLayout(device.device, &pPipelineLayoutCreateInfo, null, out pipeline.pipelineLayout));
        }
Esempio n. 13
0
        private void GrowBuffers(VkCommandBufferLevel level, uint numBuffers)
        {
            NativeList <VkCommandBuffer> buffers =
                level == VkCommandBufferLevel.Primary ? primaryCmdBuffers : secondaryCmdBuffers;

            uint oldBuffers = buffers.Count;

            if (numBuffers <= oldBuffers)
            {
                return;
            }

            // Create one command buffer for each swap chain image and reuse for rendering
            buffers.Resize(numBuffers);
            buffers.Count = numBuffers;

            if (buffers.Count > MAX_BUFFERS)
            {
                throw new InvalidOperationException("Hit max buffer amount. Please check if buffers are not being reused correctly.");
            }

            VkCommandBufferAllocateInfo cmdBufAllocateInfo =
                Initializers.CommandBufferAllocateInfo(vkCmdPool, level, buffers.Count - oldBuffers);

            Util.CheckResult(vkAllocateCommandBuffers(device.device, ref cmdBufAllocateInfo, (VkCommandBuffer *)buffers.GetAddress(oldBuffers)));

            var queue =
                level == VkCommandBufferLevel.Primary ? freePrimaryBuffers : freeSecondaryBuffers;

            for (uint i = oldBuffers; i < buffers.Count; i++)
            {
                queue.Enqueue(buffers[i]);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 1D convolution layer (e.g. temporal convolution). This layer creates a convolution kernel that is convolved with the layer input over a single spatial (or temporal) dimension to produce a tensor of outputs. If use_bias is True, a bias vector is created and added to the outputs. Finally, if activation is not None, it is applied to the outputs as well.
        /// </summary>
        /// <param name="layer">The output of the last layer.</param>
        /// <param name="channels">Integer, the dimensionality of the output space</param>
        /// <param name="kernalSize">An integer specifying the length of the 1D convolution window.</param>
        /// <param name="strides">An integer specifying the stride length of the convolution.</param>
        /// <param name="padding">Boolean, if true results in padding the input such that the output has the same length as the original input.</param>
        /// <param name="dialation">An integer specifying the dilation rate to use for dilated convolution. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any strides value != 1.</param>
        /// <param name="activation">Activation function to use. If you don't specify anything, no activation is applied (ie. "linear" activation: a(x) = x). <see cref="SiaNet.Common.OptActivations"/></param>
        /// <param name="useBias">Boolean, whether the layer uses a bias vector.</param>
        /// <param name="weightInitializer">Initializer for the kernel weights matrix. <see cref="SiaNet.Common.OptInitializers"/></param>
        /// <param name="biasInitializer">Initializer for the bias vector. <see cref="SiaNet.Common.OptInitializers"/></param>
        /// <returns></returns>
        public static Function Conv1D(Variable layer, int channels, int kernalSize, int strides=1, bool padding=true, int dialation=1, string activation = OptActivations.None, bool useBias = false, string weightInitializer = OptInitializers.Xavier, string biasInitializer = OptInitializers.Zeros)
        {
            Parameter convParams = null;
            Function conv = null;
            if (layer.Shape.Rank > 1)
            {
                int numInputChannels = layer.Shape[layer.Shape.Rank - 1];
                convParams = new Parameter(new int[] { kernalSize, numInputChannels, channels }, DataType.Float, Initializers.Get(weightInitializer), GlobalParameters.Device);
                conv = CNTKLib.Convolution(convParams, layer, new int[] { strides }, new BoolVector(new bool[] { true }), new BoolVector(new bool[] { padding, false, false }), new int[] { dialation });
            }
            else
            {
                convParams = new Parameter(new int[] { kernalSize, channels }, DataType.Float, Initializers.Get(weightInitializer), GlobalParameters.Device);
                conv = CNTKLib.Convolution(convParams, layer, new int[] { strides }, new BoolVector(new bool[] { true }), new BoolVector(new bool[] { padding }), new int[] { dialation });
            }

            Parameter bias = null;
            if (useBias)
            {
                bias = new Parameter(conv.Output.Shape, DataType.Float, Initializers.Get(biasInitializer), GlobalParameters.Device);
                conv = CNTKLib.Plus(bias, conv);
            }
            
            return Basic.Activation(conv, activation);
        }
Esempio n. 15
0
        public override TElement MapToType <TElement>(Document document, Sitecore.ContentSearch.Linq.Methods.SelectMethod selectMethod, IEnumerable <IFieldQueryTranslator> virtualFieldProcessors, Sitecore.ContentSearch.Security.SearchSecurityOptions securityOptions)
        {
            // if the result type is not IStandardTemplateItem, use the default functionality
            if (!typeof(IStandardTemplateItem).IsAssignableFrom(typeof(TElement)))
            {
                return(base.MapToType <TElement>(document, selectMethod, virtualFieldProcessors, securityOptions));
            }

            // initializers can't really support sub-selects of objects. Error if that's what's being used.
            if (selectMethod != null)
            {
                throw new NotSupportedException("Using Select on a Synthesis object type is supported. Convert the query to a list or array before selecting, then select using LINQ to objects.");
            }

            var fields = ExtractFieldsFromDocument(document, virtualFieldProcessors);

            ShortID templateId;

            if (!fields.ContainsKey("_template") || !ShortID.TryParse(fields["_template"], out templateId))
            {
                templateId = ID.Null.ToShortID();
            }

            var result = Initializers.GetInitializer(templateId.ToID()).CreateInstanceFromSearch(fields);

            if (result is TElement)
            {
                return((TElement)result);
            }

            return(default(TElement));
        }
Esempio n. 16
0
    private void CreateAndExecuteInitializers()
    {
        IJob[] initializers;

        using (var creatorScope = Context.BeginScope(this, TransactionScopeKind.Suppress, LogSeverity.Information))
        {
            var builder = new ResilientSqlScopeProcessBuilder()
            {
                Scope = this
            };
            Initializers.Invoke(builder);
            initializers = builder.Jobs.Where(x => x != null).ToArray();

            Context.Log(LogSeverity.Information, this, "created {InitializerCount} initializers", initializers?.Length ?? 0);
        }

        if (initializers?.Length > 0)
        {
            Context.Log(LogSeverity.Information, this, "starting initializers");

            foreach (var process in initializers)
            {
                var preExceptionCount = Context.ExceptionCount;

                process.Execute(this);

                if (Context.ExceptionCount > preExceptionCount)
                {
                    break;
                }
            }
        }
    }
Esempio n. 17
0
        /// <summary>
        /// Builds the RNN.
        /// </summary>
        /// <param name="inputDim">The input dim.</param>
        /// <param name="hiddenSize">Size of the hidden.</param>
        /// <param name="numLayers">The number layers.</param>
        /// <param name="bidirectional">if set to <c>true</c> [bidirectional].</param>
        /// <param name="weightInitializer">The weight initializer.</param>
        /// <param name="rnnName">Name of the RNN.</param>
        /// <returns></returns>
        private static Function BuildRNN(int inputDim, uint hiddenSize, uint numLayers, bool bidirectional = false, string weightInitializer = OptInitializers.Xavier, string rnnName = "")
        {
            int[] s       = { inputDim };
            var   weights = new Parameter(s, DataType.Float, Initializers.Get(weightInitializer), GlobalParameters.Device);

            return(CNTKLib.OptimizedRNNStack(Variable.InputVariable(new int[] { inputDim }, DataType.Float), weights, hiddenSize, numLayers, bidirectional, rnnName));
        }
        public ConventionBasedCodingStyle Merge(ConventionBasedCodingStyle other)
        {
            AddTypes(other.types);

            Type.Merge(other.Type);
            TypeIsValue.Merge(other.TypeIsValue);
            TypeIsView.Merge(other.TypeIsView);
            IdExtractor.Merge(other.IdExtractor);
            ValueExtractor.Merge(other.ValueExtractor);
            Locator.Merge(other.Locator);
            Converters.Merge(other.Converters);
            StaticInstances.Merge(other.StaticInstances);
            Initializers.Merge(other.Initializers);
            Datas.Merge(other.Datas);
            Operations.Merge(other.Operations);

            DataFetchedEagerly.Merge(other.DataFetchedEagerly);

            ParameterIsOptional.Merge(other.ParameterIsOptional);
            ParameterDefaultValue.Merge(other.ParameterDefaultValue);

            Module.Merge(other.Module);
            TypeName.Merge(other.TypeName);
            DataName.Merge(other.DataName);
            OperationName.Merge(other.OperationName);
            ParameterName.Merge(other.ParameterName);

            TypeMarks.Merge(other.TypeMarks);
            InitializerMarks.Merge(other.InitializerMarks);
            DataMarks.Merge(other.DataMarks);
            OperationMarks.Merge(other.OperationMarks);
            ParameterMarks.Merge(other.ParameterMarks);

            return(this);
        }
        private void FillRepositoryWithPreviousResults(IMetricsRepository repository)
        {
            Enumerable.Range(1, 31)
            .ToList()
            .ForEach(pastDay =>
            {
                var pastResultsEU = new Dictionary <IAnalyzer <IMetric>, IMetric>
                {
                    { Initializers.Size(), new DoubleMetric(MetricEntity.Dataset, "*", "Size", Math.Floor(pastDay / 3.0)) },
                    { Initializers.Mean("sales"), new DoubleMetric(MetricEntity.Column, "sales", "Mean", pastDay * 7) }
                };

                var pastResultsNA = new Dictionary <IAnalyzer <IMetric>, IMetric>
                {
                    { Initializers.Size(), new DoubleMetric(MetricEntity.Dataset, "*", "Size", pastDay) },
                    { Initializers.Mean("sales"), new DoubleMetric(MetricEntity.Column, "sales", "Mean", pastDay * 9) }
                };

                var analyzerContextEU = new AnalyzerContext(pastResultsEU);
                var analyzerContextNA = new AnalyzerContext(pastResultsNA);

                long dateTime = CreateDate(2018, 7, pastDay);

                repository.Save(new ResultKey(dateTime, new Dictionary <string, string> {
                    { "marketplace", "EU" }
                }),
                                analyzerContextEU);

                repository.Save(new ResultKey(dateTime, new Dictionary <string, string> {
                    { "marketplace", "NA" }
                }),
                                analyzerContextNA);
            });
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="EditableListInitExpression" /> class.
 /// </summary>
 /// <param name="listInit">
 ///     The <see cref="ListInitExpression" /> .
 /// </param>
 public EditableListInitExpression(ListInitExpression listInit) : this()
 {
     NewExpression = CreateEditableExpression(listInit.NewExpression);
     foreach (ElementInit e in listInit.Initializers)
     {
         Initializers.Add(new EditableElementInit(e));
     }
 }
Esempio n. 21
0
 public override Ust[] GetChildren()
 {
     if (Initializers != null)
     {
         return(Initializers.ToArray());
     }
     return(new Ust[0]);
 }
 public void save_should_ignore_failed_result_metrics_when_saving()
 {
     Dictionary <IAnalyzer <IMetric>, IMetric> metrics = new Dictionary <IAnalyzer <IMetric>, IMetric>
     {
         {
             Initializers.Size(Option <string> .None),
             new DoubleMetric(MetricEntity.Column, "Size", "*", Try <double> .From(() => 5.0))
         },
Esempio n. 23
0
 void M()
 {
     var i = new Initializers("")
     {
         F = 0, G = 1
     };
     var iz = new Initializers[] { i, new Initializers("") };
 }
Esempio n. 24
0
        /// <summary>
        /// CreateExpression generates a CodeExpression based on the given member data.
        /// </summary>
        /// <returns>Generated CodeExpression.</returns>
        public CodeExpression CreateExpression()
        {
            var createType = new CodeTypeReference(Type);

            return(Initializers != null
                ? new CodeArrayCreateExpression(createType, Initializers.Select(i => i.CreateExpression()).ToArray())
                : new CodeArrayCreateExpression(createType, Size));
        }
Esempio n. 25
0
        public void SetViewportScissor(RenderContext context)
        {
            VkViewport viewport = Initializers.viewport((float)context.currentFrameBuffer.swapchain.width, (float)context.currentFrameBuffer.swapchain.height, 0.0f, 1.0f);

            vkCmdSetViewport(vkCmd, 0, 1, &viewport);

            VkRect2D scissor = Initializers.rect2D(context.currentFrameBuffer.swapchain.width, context.currentFrameBuffer.swapchain.height, 0, 0);

            vkCmdSetScissor(vkCmd, 0, 1, &scissor);
        }
Esempio n. 26
0
        /// <summary>
        /// Builds the RNN.
        /// </summary>
        /// <param name="inputDim">The input dim.</param>
        /// <param name="hiddenSize">Size of the hidden.</param>
        /// <param name="numLayers">The number layers.</param>
        /// <param name="bidirectional">if set to <c>true</c> [bidirectional].</param>
        /// <param name="weightInitializer">The weight initializer.</param>
        /// <param name="rnnName">Name of the RNN.</param>
        /// <returns></returns>
        private static Function BuildRNN(int[] shape, int dim, uint hiddenSize, uint numLayers, bool bidirectional = false, string weightInitializer = OptInitializers.Xavier, string rnnName = "")
        {
            List<int> s = new List<int>();
            s.AddRange(shape);
            s.Add(dim);

            var weights = new Parameter(s.ToArray(), DataType.Float, Initializers.Get(weightInitializer), GlobalParameters.Device);
            
            return CNTKLib.OptimizedRNNStack(Variable.InputVariable(s.ToArray(), DataType.Float), weights, hiddenSize, numLayers, bidirectional, rnnName);
        }
 public void analysis_results_serialization_with_mixed_Values_should_fail()
 {
     ArgumentException sampleException = new ArgumentException("Some");
     AnalyzerContext   analyzerContextWithMixedValues = new AnalyzerContext(
         new Dictionary <IAnalyzer <IMetric>, IMetric>
     {
         {
             Initializers.Size(Option <string> .None),
             new DoubleMetric(MetricEntity.Column, "Size", "*", Try <double> .From(() => 5.0))
         },
        private VerificationResult CreateAnomalyChecksAndRunEverything(
            DataFrame data,
            IMetricsRepository repository,
            Check otherCheck,
            IEnumerable <IAnalyzer <IMetric> > additionalRequiredAnalyzers)
        {
            // We only want to use historic data with the EU tag for the anomaly checks since the new
            // data point is from the EU marketplace
            var filterEU = new Dictionary <string, string> {
                { "marketplace", "EU" }
            };

            // We only want to use data points before the date time associated with the current
            // data point and only ones that are from 2018
            var afterDateTime  = CreateDate(2018, 1, 1);
            var beforeDateTime = CreateDate(2018, 8, 1);

            // Config for the size anomaly check
            var sizeAnomalyCheckConfig = new AnomalyCheckConfig(CheckLevel.Error, "Size only increases",
                                                                filterEU, afterDateTime, beforeDateTime);
            var sizeAnomalyDetectionStrategy = new AbsoluteChangeStrategy(0);

            // Config for the mean sales anomaly check
            var meanSalesAnomalyCheckConfig = new AnomalyCheckConfig(
                CheckLevel.Warning,
                "Sales mean within 2 standard deviations",
                filterEU,
                afterDateTime,
                beforeDateTime
                );

            var meanSalesAnomalyDetectionStrategy = new OnlineNormalStrategy(upperDeviationFactor: 2, lowerDeviationFactor: Option <double> .None,
                                                                             ignoreAnomalies: false);

            // ResultKey to be used when saving the results of this run
            var currentRunResultKey =
                new ResultKey(CreateDate(2018, 8, 1), new Dictionary <string, string> {
                { "marketplace", "EU" }
            });


            return(new VerificationSuite()
                   .OnData(data)
                   .AddCheck(otherCheck)
                   .AddRequiredAnalyzers(additionalRequiredAnalyzers)
                   .UseRepository(repository)
                   // Add the Size anomaly check
                   .AddAnomalyCheck(sizeAnomalyDetectionStrategy, Initializers.Size(), sizeAnomalyCheckConfig)
                   // Add the Mean sales anomaly check
                   .AddAnomalyCheck(meanSalesAnomalyDetectionStrategy, Initializers.Mean("sales"),
                                    meanSalesAnomalyCheckConfig)
                   // Save new data point in the repository after we calculated everything
                   .SaveOrAppendResult(currentRunResultKey)
                   .Run());
        }
Esempio n. 29
0
        public override string GetPyCode(PyEmitStyle style)
        {
            if (Initializers.Count == 0)
            {
                return("dict()");
            }
            var initializers = Initializers.Select(a => a.Key.GetPyCode(style) + ":" + a.Value.GetPyCode(style));
            var code         = string.Join(", ", initializers);

            return("{" + code + "}");
        }
Esempio n. 30
0
        public override ICollection <Type> GetKnownTypes([Optional] Container container)
        {
            Console.WriteLine("List Init Expression Node KnownType");

            var totalTypes = base.GetKnownTypes(container).Concat(new [] { this.GetType(), Initializers?.GetType() })
                             .Concat(NewExpression?.GetKnownTypes(container) ?? Enumerable.Empty <Type>())
                             .Concat(Initializers?.SelectMany(e => e?.GetKnownTypes(container)).ToList() ?? Enumerable.Empty <Type>())
                             .ToList();

            return(totalTypes);
        }
Esempio n. 31
0
        public static void Initialize(Initializers ths)
        {
            Common.StringBuilder msg = new Common.StringBuilder("Initialize");

            try
            {
                GameUtils.BeginLoadEvent("GameInit");
                for (int i = 0x0; i < ths.mInitializerRecords.Count; i++)
                {
                    Initializers.Record record = ths.mInitializerRecords[i];
                    GameUtils.BeginLoadEvent("GameInit/" + record.ToString());

                    Initializers.Action action = record.Instantiate();

                    if (action.Valid)
                    {
                        msg += Common.NewLine + "Instance: " + action.mInstance;
                        msg += Common.NewLine + "Init: " + action.mInit;
                        msg += Common.NewLine + "Type: " + action.mType;
                        Traveler.InsanityWriteLog(msg);

                        try
                        {
                            string header = action.mType + " - " + action.mInit;
                            using (Common.TestSpan span = new Common.TestSpan(Common.ExternalTimeSpanLogger.sLogger, header))
                            {
                                if (header == "Sims3.Gameplay.CAS.SimDescription - Void PostLoadFixUp()")
                                {
                                    PostLoadFixUp();
                                }
                                else
                                {
                                    action.DoInit();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Common.Exception(msg, e);
                        }
                    }

                    GameUtils.EndLoadEvent();
                }
                GameUtils.EndLoadEvent();
            }
            finally
            {
                Common.WriteLog(msg);
            }
        }
Esempio n. 32
0
 public VariableDeclarator(VariableSubDeclarator dec, Initializers init)
 {
     declaration = dec;
     initialization = init;
 }
Esempio n. 33
0
 /// <summary>
 /// Initialize according to property setting.
 /// </summary>
 public void Initialize(Initializers mvarinitializers)
 {
     switch (mvarinitializers)
     {
         case Initializers.GetAll:
             GetAll();
             break;
         case Initializers.GetBiosInfo:
             GetBiosInfo();
             break;
         case Initializers.GetCpuInfo:
             GetCpuInfo();
             break;
         case Initializers.GetDriveInformation:
             GetDriveInformation();
             break;
         case Initializers.GetNetAdaptorInfo:
             GetNetAdaptorInfo();
             break;
         case Initializers.GetNetInterfaceInfo:
             GetNetInterfaceInfo();
             break;
         case Initializers.GetSoundInfo:
             GetSoundInfo();
             break;
         case Initializers.GetVideoInfo:
             GetVideoInfo();
             break;
         case Initializers.GetVolumeInfo:
             GetVolumeInfo();
             break;
         case Initializers.GetNone:
             break;
         case Initializers.GetServiceInfo:
             GetServiceInfo();
             break;
         default:
             GetAll();
             break;
     }
 }
Esempio n. 34
0
        public override void Startup()
        {
            Common.StringBuilder msg = new Common.StringBuilder("InWorldStateEx:Startup");
            Traveler.InsanityWriteLog(msg);

            try
            {
                // StateMachineState:Startup()
                mBaseCallFlag |= BaseCallFlag.kStartup;
                //base.Startup();

                msg += Common.NewLine + "A";
                Traveler.InsanityWriteLog(msg);

                Sims3.Gameplay.UI.Responder.GameStartup();

                mEnteredFromTravelling = GameStates.IsTravelling;

                bool flag = false;

                try
                {
                    ModalDialog.EnableModalDialogs = false;

                    if (World.IsEditInGameFromWBMode())
                    {
                        Sims3.Gameplay.Autonomy.Autonomy.DisableMoodContributors = true;
                    }

                    msg += Common.NewLine + "B";
                    Traveler.InsanityWriteLog(msg);

                    mStateMachine = StateMachine.Create(0x1, "InWorld");
                    mSubStates[0] = new LiveModeStateEx(GameStates.IsMovingWorlds);  // Custom
                    mSubStates[1] = new BuildModeState();
                    mSubStates[2] = new BuyModeState();
                    mSubStates[12] = new ShoppingModeState();
                    mSubStates[3] = new CASFullModeState();
                    mSubStates[4] = new CASDresserModeState();
                    mSubStates[5] = new CASMirrorModeState();
                    mSubStates[6] = new CASTattooModeState();
                    mSubStates[7] = new CASStylistModeState();
                    mSubStates[8] = new CASTackModeState();
                    mSubStates[9] = new CASCollarModeState();
                    mSubStates[10] = new CASSurgeryFaceModeState();
                    mSubStates[11] = new CASSurgeryBodyModeState();
                    mSubStates[15] = new PlayFlowStateEx(); // Custom
                    mSubStates[14] = new EditTownStateEx(); // Custom
                    mSubStates[16] = new BlueprintModeState();
                    mSubStates[17] = new CASMermaidModeState();
                    mSubStates[0x12] = new CABModeState();
                    mSubStates[0x13] = new CABModeEditState();

                    foreach (InWorldSubState state in mSubStates)
                    {
                        mStateMachine.AddState(state);
                    }

                    msg += Common.NewLine + "C";
                    Traveler.InsanityWriteLog(msg);

                    StateMachineManager.AddMachine(mStateMachine);
                    if (GameStates.IsTravelling || GameStates.IsEditingOtherTown)
                    {
                        try
                        {
                            Sims3.Gameplay.WorldBuilderUtil.CharacterImportOnGameLoad.RemapSimDescriptionIds();
                        }
                        catch (Exception e)
                        {
                            Common.DebugException("RemapSimDescriptionIds", e);
                        }
                    }
                    else
                    {
                        CrossWorldControl.sRetention.RestoreHouseholds();
                    }

                    msg += Common.NewLine + "D";
                    Traveler.InsanityWriteLog(msg);

                    if (GameStates.IsTravelling)
                    {
                        msg += Common.NewLine + "E1";
                        Traveler.InsanityWriteLog(msg);

                        bool fail = false;
                        if (!GameStatesEx.ImportTravellingHousehold())
                        {
                            msg += Common.NewLine + "E3";

                            fail = true;
                        }

                        if ((GameStates.TravelHousehold == null) && (GameStates.sTravelData.mState == GameStates.TravelData.TravelState.StartVacation))
                        {
                            msg += Common.NewLine + "E4";

                            fail = true;
                        }

                        if (fail)
                        {
                            msg += Common.NewLine + "E5";
                            Traveler.InsanityWriteLog(msg);

                            GameStates.sStartupState = SubState.EditTown;

                            GameStates.ClearTravelStatics();

                            WorldData.SetVacationWorld(true, true);
                        }
                    }
                    else if ((!GameStates.IsEditingOtherTown) && (GameStates.HasTravelData) && (GameStates.TravelHousehold == null))
                    {
                        switch (GameUtils.GetCurrentWorldType())
                        {
                            case WorldType.Base:
                            case WorldType.Downtown:
                                msg += Common.NewLine + "E2";
                                Traveler.InsanityWriteLog(msg);

                                GameStates.ClearTravelStatics();
                                break;
                        }
                    }

                    // Custom
                    if (GameStates.sMovingWorldData != null)
                    {
                        Household.IsTravelImport = true;
                    }

                    msg += Common.NewLine + "F1";
                    Traveler.InsanityWriteLog(msg);

                    List<Household> households = new List<Household>(Household.sHouseholdList);
                    foreach (Household a in households)
                    {
                        if ((a.LotHome != null) && (a.LotHome.Household == null))
                        {
                            a.LotHome.mHousehold = a;
                        }

                        foreach (SimDescription simA in Households.All(a))
                        {
                            // Must be validated prior to SimDescription:PostLoadFixup()
                            if (simA.GameObjectRelationships != null)
                            {
                                for(int index=simA.GameObjectRelationships.Count-1; index >=0; index--)
                                {
                                    if ((simA.GameObjectRelationships[index] == null) ||
                                        (simA.GameObjectRelationships[index].GameObjectDescription == null) ||
                                        (simA.GameObjectRelationships[index].GameObjectDescription.GameObject == null) ||
                                        (!Objects.IsValid(simA.GameObjectRelationships[index].GameObjectDescription.GameObject.ObjectId)))
                                    {
                                        simA.GameObjectRelationships.RemoveAt(index);
                                    }
                                }
                            }

                            foreach (Household b in households)
                            {
                                if (a == b) continue;

                                if (!b.Contains(simA)) continue;

                                if (b.NumMembers == 1) continue;

                                try
                                {
                                    b.Remove(simA, false);

                                    msg += Common.NewLine + "Duplicate: " + simA.FullName;
                                }
                                catch (Exception e)
                                {
                                    Common.Exception(simA, e);
                                }
                            }
                        }
                    }

                    msg += Common.NewLine + "F2";
                    Traveler.InsanityWriteLog(msg);

                    // Required to ensure that all homeworld specific data is fixed up properly (specifically careers)
                    using (BaseWorldReversion reversion = new BaseWorldReversion())
                    {
                        // Reset this, to allow the Seasons Manager to activate properly
                        SeasonsManager.sSeasonsValidForWorld = SeasonsManager.Validity.Undetermined;

                        try
                        {
                            mPostWorldInitializers = new Initializers("PostWorldInitializers", this);

                            using (CareerStore store = new CareerStore())
                            {
                                //InitializersEx.Initialize(mPostWorldInitializers);
                                mPostWorldInitializers.Initialize();
                            }
                        }
                        catch (Exception e)
                        {
                            Traveler.InsanityException(msg, e);
                        }
                    }

                    msg += Common.NewLine + "G1";
                    Traveler.InsanityWriteLog(msg);

                    try
                    {
                        if (GameStates.TravelHousehold != null)
                        {
                            LinkToTravelHousehold();

                            WorldName worldName = GameUtils.GetCurrentWorld();

                            switch (worldName)
                            {
                                case WorldName.China:
                                case WorldName.Egypt:
                                case WorldName.France:
                                    break;
                                default:
                                    foreach (SimDescription sim in Households.All(GameStates.TravelHousehold))
                                    {
                                        if (sim.VisaManager == null) continue;

                                        WorldData.OnLoadFixup(sim.VisaManager);

                                        sim.VisaManager.SetVisaLevel(worldName, 3);
                                    }
                                    break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Traveler.InsanityException(msg, e);
                    }

                    msg += Common.NewLine + "G2";
                    Traveler.InsanityWriteLog(msg);

                    List<SimDescription> dyingSims = null;
                    if (GameStates.IsTravelling)
                    {
                        dyingSims = GameStatesEx.PostTravelingFixUp();
                    }

                    msg += Common.NewLine + "H";
                    Traveler.InsanityWriteLog(msg);

                    if (GameStates.IsEditingOtherTown)
                    {
                        GameStates.PostLoadEditTownFixup();
                    }

                    msg += Common.NewLine + "I";
                    Traveler.InsanityWriteLog(msg);

                    // We must stop the travel actions from running if the homeworld is an EA vacation world
                    WorldData.SetVacationWorld(true, false);

                    GameStates.NullEditTownDataDataIfEditingOriginalStartingWorld();
                    try
                    {
                        if (GameUtils.IsAnyTravelBasedWorld())
                        {
                            if ((dyingSims != null) && (AgingManager.NumberAgingYearsElapsed != -1f))
                            {
                                float yearsGone = GameStates.NumberAgingYearsElapsed - AgingManager.NumberAgingYearsElapsed;

                                // Custom function
                                FixUpAfterTravel(yearsGone, dyingSims);
                            }
                            AgingManager.NumberAgingYearsElapsed = GameStates.NumberAgingYearsElapsed;
                        }
                    }
                    catch (Exception e)
                    {
                        Traveler.InsanityException(msg, e);
                    }

                    msg += Common.NewLine + "J";
                    Traveler.InsanityWriteLog(msg);

                    Sims3.Gameplay.Gameflow.GameSpeed pause = Sims3.Gameplay.Gameflow.GameSpeed.Pause;

                    if (GameStates.StartupState == SubState.LiveMode)
                    {
                        flag = !GameStates.IsEditingOtherTown && (((GameStates.ForceStateChange || !PlayFlowModel.Singleton.GameEntryLive) || (PlumbBob.SelectedActor != null)) || GameStates.IsTravelling);
                        if (flag)
                        {
                            if (Sims3.Gameplay.Gameflow.sGameLoadedFromWorldFile)
                            {
                                pause = Sims3.SimIFace.Gameflow.GameSpeed.Normal;
                            }
                            else
                            {
                                pause = Sims3.Gameplay.Gameflow.sPersistedGameSpeed;
                            }
                        }
                    }

                    msg += Common.NewLine + "K";
                    Traveler.InsanityWriteLog(msg);

                    Sims3.Gameplay.Gameflow.sGameLoadedFromWorldFile = false;
                    string s = CommandLine.FindSwitch("speed");
                    if (s != null)
                    {
                        int num2;
                        if (int.TryParse(s, out num2))
                        {
                            pause = (Sims3.Gameplay.Gameflow.GameSpeed)num2;
                        }
                        else
                        {
                            ParserFunctions.TryParseEnum<Sims3.Gameplay.Gameflow.GameSpeed>(s, out pause, Sims3.Gameplay.Gameflow.GameSpeed.Normal);
                        }
                    }

                    msg += Common.NewLine + "L";
                    Traveler.InsanityWriteLog(msg);

                    Sims3.Gameplay.Gameflow.SetGameSpeed(pause, Sims3.Gameplay.Gameflow.SetGameSpeedContext.GameStates);
                    NotificationManager.Load();
                    MainMenu.TriggerPendingFsiWorldNotifications();
                }
                finally
                {
                    ModalDialog.EnableModalDialogs = true;
                }

                if (SocialFeatures.Accounts.IsLoggedIn())
                {
                    Notify(0, 0, 0L);
                }

                switch (GameStates.StartupState)
                {
                    case SubState.EditTown:
                        msg += Common.NewLine + "StartupState: EditTown";

                        GameUtils.EnableSceneDraw(true);
                        LoadingScreenController.Unload();
                        GotoEditTown();
                        break;

                    case SubState.PlayFlow:
                        if (World.IsEditInGameFromWBMode())
                        {
                            msg += Common.NewLine + "StartupState: PlayFlow (A)";

                            GameUtils.EnableSceneDraw(true);
                            LoadingScreenController.Unload();
                            GotoLiveMode();
                        }
                        else if (!PlayFlowModel.PlayFlowEnabled || !PlayFlowModel.Singleton.GameEntryLive)
                        {
                            msg += Common.NewLine + "StartupState: PlayFlow (B)";

                            GameUtils.EnableSceneDraw(true);
                            LoadingScreenController.Unload();
                            GotoLiveMode();
                        }
                        else
                        {
                            msg += Common.NewLine + "StartupState: PlayFlow (C)";

                            GotoPlayFlow();
                        }
                        break;

                    case SubState.LiveMode:
                        // Custom
                        if (((!GameUtils.IsOnVacation() && !GameUtils.IsFutureWorld()) || EditTownModel.IsAnyLotBaseCampStatic() || EditTownModelEx.IsAnyUnoccupiedLotStatic()) && flag)
                        {
                            bool directToGame = false;
                            if (!GameStates.IsTravelling) 
                            {
                                // Entering an existing save
                                directToGame = true;
                            }
                            else if (EditTownModel.IsAnyLotBaseCampStatic())
                            {
                                // Normal transition to base camp
                                directToGame = true;
                            }
                            else if (!GameUtils.IsInstalled(ProductVersion.EP9))
                            {
                                // Use custom household selection
                                directToGame = true;
                            }

                            // Custom
                            if ((flag) && (directToGame))
                            {
                                msg += Common.NewLine + "StartupState: LiveMode (A)";

                                GotoLiveMode();
                                break;
                            }
                            else
                            {
                                msg += Common.NewLine + "StartupState: LiveMode (C)";

                                GameUtils.EnableSceneDraw(true);
                                LoadingScreenController.Unload();
                                GotoPlayFlow();
                                break;
                            }
                        }

                        msg += Common.NewLine + "StartupState: LiveMode (B)";

                        GameUtils.EnableSceneDraw(true);
                        LoadingScreenController.Unload();
                        GotoEditTown();
                        break;
                }

                msg += Common.NewLine + "M";
                Traveler.InsanityWriteLog(msg);

                if (Sims3.Gameplay.Gameflow.sShowObjectReplacedWarning)
                {
                    SimpleMessageDialog.Show(Common.LocalizeEAString("Ui/Warning/LoadGame:Warning"), Common.LocalizeEAString("Ui/Warning/LoadGame:ReplacedObjects"), ModalDialog.PauseMode.PauseSimulator);
                    Sims3.Gameplay.Gameflow.sShowObjectReplacedWarning = false;
                }
            }
            catch (Exception e)
            {
                Traveler.InsanityException(msg, e);
            }
            finally
            {
                //Common.WriteLog(msg);
            }
        }
Esempio n. 35
0
        public override void Startup()
        {
            string msg = "InWorldStateEx:Startup";
            CRAPJailBreak.InsanityWriteLog(msg);

            try
            {
                // StateMachineState:Startup()
                mBaseCallFlag |= BaseCallFlag.kStartup;
                //base.Startup();

                msg += Common.NewLine + "A";
                CRAPJailBreak.InsanityWriteLog(msg);

                Sims3.Gameplay.UI.Responder.GameStartup();

                bool flag = false;

                try
                {
                    ModalDialog.EnableModalDialogs = false;

                    if (World.IsEditInGameFromWBMode())
                    {
                        Sims3.Gameplay.Autonomy.Autonomy.DisableMoodContributors = true;
                    }

                    msg += Common.NewLine + "B";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    mStateMachine = StateMachine.Create(0x1, "InWorld");
                    mSubStates[0x0] = new LiveModeState();
                    mSubStates[0x1] = new BuildModeState();
                    mSubStates[0x2] = new BuyModeState();
                    mSubStates[0xc] = new ShoppingModeState();
                    mSubStates[0x3] = new CASFullModeState();
                    mSubStates[0x4] = new CASDresserModeState();
                    mSubStates[0x5] = new CASMirrorModeState();
                    mSubStates[0x6] = new CASTattooModeState();
                    mSubStates[0x7] = new CASStylistModeState();
                    mSubStates[0x8] = new CASTackModeState();
                    mSubStates[0x9] = new CASCollarModeState();
                    mSubStates[0xa] = new CASSurgeryFaceModeState();
                    mSubStates[0xb] = new CASSurgeryBodyModeState();
                    mSubStates[0xf] = new PlayFlowState();
                    mSubStates[0xe] = new EditTownState();

                    foreach (InWorldSubState state in mSubStates)
                    {
                        mStateMachine.AddState(state);
                    }

                    msg += Common.NewLine + "C";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    StateMachineManager.AddMachine(mStateMachine);
                    if (GameStates.IsTravelling || GameStates.IsEditingOtherTown)
                    {
                        try
                        {
                            Sims3.Gameplay.WorldBuilderUtil.CharacterImportOnGameLoad.RemapSimDescriptionIds();
                        }
                        catch (Exception e)
                        {
                            Common.DebugException("RemapSimDescriptionIds", e);
                        }
                    }

                    msg += Common.NewLine + "D";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    if (GameStates.IsTravelling)
                    {
                        msg += Common.NewLine + "E1";
                        CRAPJailBreak.InsanityWriteLog(msg);

                        GameStates.ImportTravellingHousehold();
                    }
                    else if ((!GameStates.IsEditingOtherTown) && (GameUtils.GetCurrentWorldType() == WorldType.Base) && (GameStates.HasTravelData) && (GameStates.TravelHousehold == null))
                    {
                        msg += Common.NewLine + "E2";
                        CRAPJailBreak.InsanityWriteLog(msg);

                        GameStates.ClearTravelStatics();
                    }

                    msg += Common.NewLine + "F";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    Sim selectedActor = PlumbBob.SelectedActor;
                    if (selectedActor != null)
                    {
                        msg += Common.NewLine + "SelectedActor: " + selectedActor.FullName;
                        msg += Common.NewLine + "SkillManager: " + (selectedActor.SkillManager != null);
                        msg += Common.NewLine + "SocialComponent: " + (selectedActor.SocialComponent != null);
                        msg += Common.NewLine + "CareerManager: " + (selectedActor.CareerManager != null);
                        msg += Common.NewLine + "TraitManager: " + (selectedActor.TraitManager != null);
                        msg += Common.NewLine + "SimDescription: " + (selectedActor.SimDescription != null);
                        msg += Common.NewLine + "InteractionQueue: " + (selectedActor.InteractionQueue != null);
                        msg += Common.NewLine + "OccultManager: " + (selectedActor.OccultManager != null);
                    }
                    else
                    {
                        msg += Common.NewLine + "No SelectedActor";
                    }

                    CRAPJailBreak.InsanityWriteLog(msg);

                    try
                    {
                        mPostWorldInitializers = new Initializers("PostWorldInitializers", this);

                        /*
                        for (int i = 0; i < mPostWorldInitializers.mInitializerRecords.Count; i++)
                        {
                            Initializers.Record record = mPostWorldInitializers.mInitializerRecords[i];

                            if ((record.mTypeName.Replace(" ", "") == "Sims3.Gameplay.CAS.SimDescription,Sims3GameplaySystems") &&
                                (record.mInitName == "PostLoadFixUp"))
                            {
                                record.mTypeName = typeof(SimDescriptionEx).FullName + "," + typeof(SimDescriptionEx).Assembly.GetName();

                                // Record is a struct, we must replace the old copy with a new one
                                mPostWorldInitializers.mInitializerRecords[i] = record;
                            }
                        }

                        //Initialize(mPostWorldInitializers);
                        */

                        mPostWorldInitializers.Initialize();
                    }
                    catch (Exception e)
                    {
                        CRAPJailBreak.InsanityException(msg, e);
                    }

                    msg += Common.NewLine + "G";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    List<SimDescription> dyingSims = null;
                    if (GameStates.IsTravelling)
                    {
                        dyingSims = GameStates.PostTravelingFixUp();
                    }

                    msg += Common.NewLine + "H";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    if (GameStates.IsEditingOtherTown)
                    {
                        GameStates.PostLoadEditTownFixup();
                    }

                    msg += Common.NewLine + "I";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    GameStates.NullEditTownDataDataIfEditingOriginalStartingWorld();
                    try
                    {
                        if (GameUtils.IsOnVacation())
                        {
                            if ((dyingSims != null) && (AgingManager.NumberAgingYearsElapsed != -1f))
                            {
                                float yearsGone = GameStates.NumberAgingYearsElapsed - AgingManager.NumberAgingYearsElapsed;

                                // Custom function
                                StoryProgressionService.FixUpAfterTravel(yearsGone, dyingSims);
                            }
                            AgingManager.NumberAgingYearsElapsed = GameStates.NumberAgingYearsElapsed;
                        }
                    }
                    catch (Exception e)
                    {
                        CRAPJailBreak.InsanityException(msg, e);
                    }

                    msg += Common.NewLine + "J";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    Sims3.Gameplay.Gameflow.GameSpeed pause = Sims3.Gameplay.Gameflow.GameSpeed.Pause;

                    if (GameStates.StartupState == SubState.LiveMode)
                    {
                        flag = !GameStates.IsEditingOtherTown && (((GameStates.ForceStateChange || !PlayFlowModel.Singleton.GameEntryLive) || (PlumbBob.SelectedActor != null)) || GameStates.IsTravelling);
                        if (flag)
                        {
                            if (Sims3.Gameplay.Gameflow.sGameLoadedFromWorldFile)
                            {
                                pause = Sims3.SimIFace.Gameflow.GameSpeed.Normal;
                            }
                            else
                            {
                                pause = Sims3.Gameplay.Gameflow.sPersistedGameSpeed;
                            }
                        }
                    }

                    msg += Common.NewLine + "K";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    Sims3.Gameplay.Gameflow.sGameLoadedFromWorldFile = false;
                    string s = CommandLine.FindSwitch("speed");
                    if (s != null)
                    {
                        int num2;
                        if (int.TryParse(s, out num2))
                        {
                            pause = (Sims3.Gameplay.Gameflow.GameSpeed)num2;
                        }
                        else
                        {
                            ParserFunctions.TryParseEnum<Sims3.Gameplay.Gameflow.GameSpeed>(s, out pause, Sims3.Gameplay.Gameflow.GameSpeed.Normal);
                        }
                    }

                    msg += Common.NewLine + "L";
                    CRAPJailBreak.InsanityWriteLog(msg);

                    Sims3.Gameplay.Gameflow.SetGameSpeed(pause, Sims3.Gameplay.Gameflow.SetGameSpeedContext.GameStates);
                    NotificationManager.Load();
                }
                finally
                {
                    ModalDialog.EnableModalDialogs = true;
                }

                switch (GameStates.StartupState)
                {
                    case SubState.EditTown:
                        msg += Common.NewLine + "StartupState: EditTown";

                        GameUtils.EnableSceneDraw(true);
                        LoadingScreenController.Unload();
                        GotoEditTown();
                        break;

                    case SubState.PlayFlow:
                        if (World.IsEditInGameFromWBMode())
                        {
                            msg += Common.NewLine + "StartupState: PlayFlow (A)";

                            GameUtils.EnableSceneDraw(true);
                            LoadingScreenController.Unload();
                            GotoLiveMode();
                        }
                        else if (!PlayFlowModel.PlayFlowEnabled || !PlayFlowModel.Singleton.GameEntryLive)
                        {
                            msg += Common.NewLine + "StartupState: PlayFlow (B)";

                            GameUtils.EnableSceneDraw(true);
                            LoadingScreenController.Unload();
                            GotoLiveMode();
                        }
                        else
                        {
                            msg += Common.NewLine + "StartupState: PlayFlow (C)";

                            GotoPlayFlow();
                        }
                        break;

                    case SubState.LiveMode:
                        if (flag)
                        {
                            msg += Common.NewLine + "StartupState: LiveMode (A)";

                            GameUtils.EnableSceneDraw(true);
                            LoadingScreenController.Unload();
                            GotoLiveMode();
                        }
                        else
                        {
                            msg += Common.NewLine + "StartupState: LiveMode (B)";

                            GameUtils.EnableSceneDraw(true);
                            LoadingScreenController.Unload();
                            GotoPlayFlow();
                        }
                        break;
                }

                msg += Common.NewLine + "M";
                CRAPJailBreak.InsanityWriteLog(msg);

                if (Sims3.Gameplay.Gameflow.sShowObjectReplacedWarning)
                {
                    SimpleMessageDialog.Show(Common.LocalizeEAString("Ui/Warning/LoadGame:Warning"), Common.LocalizeEAString("Ui/Warning/LoadGame:ReplacedObjects"), ModalDialog.PauseMode.PauseSimulator);
                    Sims3.Gameplay.Gameflow.sShowObjectReplacedWarning = false;
                }
            }
            catch (Exception e)
            {
                CRAPJailBreak.InsanityException(msg, e);
            }
        }