예제 #1
0
 public void SetRegister(string value)
 {
     if (!value.Equals(_selectedRegister.ValueString))
     {
         _selectedRegister.ValueString = value;
         if (_selectedRegister.IsValid)
         {
             try
             {
                 CircuitEvaluator eval     = CircuitEvaluator.GetInstance();
                 Register         selected = _selectedRegister.Value as Register;
                 _outputModel.Update(eval.RootRegister, selected.ToPartModel());
                 OnSelectionChanged();
             }
             catch (Exception e)
             {
                 PrintException(e);
             }
         }
         else
         {
             throw new Exception(_selectedRegister.ValidationMessage);
         }
     }
 }
예제 #2
0
파일: HomeVM.cs 프로젝트: Wowand/quantum
        public void NextStep(object parameter)
        {
            try
            {
                CircuitEvaluator eval = CircuitEvaluator.GetInstance();

                int currentStep = _model.CurrentStep;
                if (currentStep == 0)
                {
                    eval.InitFromModel(_model);
                }
                if (currentStep < _model.Steps.Count)
                {
                    StepEvaluator se            = eval.GetStepEvaluator();
                    bool          outputChanged = se.RunStep(_model.Steps[currentStep].Gates);
                    _model.CurrentStep = currentStep + 1;
                    if (outputChanged)
                    {
                        _outputModel.Update(eval.RootRegister);
                    }
                }
            }
            catch (Exception e)
            {
                PrintException(e);
            }
        }
예제 #3
0
        private object StringToValue(string text, Type type)
        {
            object toReturn = null;

            try
            {
                CircuitEvaluator eval = CircuitEvaluator.GetInstance();

                if (type == typeof(QuantumParser.RegisterRef))
                {
                    toReturn = eval.ResolveRegisterRef(text, _nextParamArray);
                }
                else if (type == typeof(QuantumParser.Register))
                {
                    toReturn = eval.ResolveRegister(text, _nextParamArray);
                }
                else
                {
                    TypeConverter converter = TypeDescriptor.GetConverter(type);
                    toReturn = converter.ConvertFromInvariantString(text);
                }
                _isValid           = true;
                _validationMessage = null;
            }
            catch (Exception ex)
            {
                _isValid           = false;
                _validationMessage = ex.Message;
            }
            return(toReturn);
        }
예제 #4
0
파일: HomeVM.cs 프로젝트: Wowand/quantum
 public void PrevStep(object parameter)
 {
     try
     {
         int currentStep = _model.CurrentStep;
         if (currentStep == 0)
         {
             Restart(parameter);
         }
         else
         {
             if (_model.CanStepBack(currentStep - 1))
             {
                 CircuitEvaluator eval          = CircuitEvaluator.GetInstance();
                 StepEvaluator    se            = eval.GetStepEvaluator();
                 bool             outputChanged = se.RunStep(_model.Steps[currentStep - 1].Gates, true);
                 _model.CurrentStep = currentStep - 1;
                 if (outputChanged)
                 {
                     _outputModel.Update(eval.RootRegister);
                 }
             }
         }
     }
     catch (Exception e)
     {
         PrintException(e);
     }
 }
예제 #5
0
        public PropertiesVM(CircuitGridVM circuitGrid, OutputGridVM outputGrid)
        {
            SelectedObject = outputGrid.SelectedObject;
            AddSelectionTracing(circuitGrid);
            AddSelectionTracing(outputGrid);

            CircuitEvaluator eval = CircuitEvaluator.GetInstance();

            _allParametrics = eval.GetExtensionGates();
        }
예제 #6
0
        private string ValueToString(object value)
        {
            Type type = value.GetType();

            if (type == typeof(RegisterRefModel))
            {
                RegisterRefModel rrm = (RegisterRefModel)value;
                StringBuilder    sb  = new StringBuilder();
                if (rrm.Register != null)
                {
                    sb.Append(rrm.Register.Name);
                }
                else
                {
                    sb.Append("root");
                }
                sb.Append("[").Append(rrm.Offset).Append("]");
                return(sb.ToString());
            }
            if (type == typeof(RegisterPartModel))
            {
                RegisterPartModel rm = (RegisterPartModel)value;
                if (rm.Register != null)
                {
                    if (rm.Width == rm.Register.Qubits.Count)
                    {
                        return(rm.Register.Name);
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append(rm.Register.Name);
                        sb.Append("[").Append(rm.Offset).Append(", ").Append(rm.Width).Append("]");
                        return(sb.ToString());
                    }
                }
                else
                {
                    CircuitEvaluator eval = CircuitEvaluator.GetInstance();
                    int rootWidth         = eval.RootRegister.Width;
                    if (rm.Width == rootWidth)
                    {
                        return("root");
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.Append("root");
                        sb.Append("[").Append(rm.Offset).Append(", ").Append(rm.Width).Append("]");
                        return(sb.ToString());
                    }
                }
            }
            return(value.ToString());
        }
예제 #7
0
파일: HomeVM.cs 프로젝트: Wowand/quantum
        public void Restart(object parameter)
        {
            try
            {
                _model.CurrentStep = 0;
                CircuitEvaluator eval = CircuitEvaluator.GetInstance();

                _outputModel = eval.InitFromModel(_model);
                OutputGrid.LoadModel(_model, _outputModel);
            }
            catch (Exception e)
            {
                PrintException(e);
            }
        }
예제 #8
0
파일: HomeVM.cs 프로젝트: Wowand/quantum
        public void GenerateFromCode(object parameter)
        {
            _window.CircuitTab.IsSelected = true;

            string code = Code;

            if (string.IsNullOrWhiteSpace(code))
            {
                return;
            }

            Parser parser = new Parser();

            try
            {
                Assembly         asmToBuild = parser.CompileForBuild(code);
                CircuitEvaluator eval       = CircuitEvaluator.GetInstance();

                Dictionary <string, List <MethodCode> > methods = parser.GetMethodsCodes(code);
                if (methods.Count > 0)
                {
                    Assembly asmToRun = parser.CompileForRun(code);
                    eval.LoadLibMethods(asmToRun);
                    eval.LoadParserMethods(asmToBuild);
                    eval.LoadMethodsCodes(methods);
                }
                Dictionary <string, List <MethodInfo> > dict = eval.GetExtensionGates();
                CompositeTools = dict.Keys.ToList();
                PropertiesPane.LoadParametrics(dict);

                ComputerModel generatedModel = parser.BuildModel(asmToBuild);
                InitFromModel(generatedModel);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
예제 #9
0
파일: HomeVM.cs 프로젝트: Wowand/quantum
        private void InitFromModel(ComputerModel model)
        {
            if (_model != null)
            {
                Dictionary <string, List <Gate> > oldComposites = _model.CompositeGates;
                Dictionary <string, List <Gate> > newComposites = model.CompositeGates;

                foreach (var pair in oldComposites)
                {
                    if (!newComposites.ContainsKey(pair.Key))
                    {
                        newComposites[pair.Key] = pair.Value;
                    }
                }
            }
            _model = model;

            CircuitGrid = new CircuitGridVM(_model);

            CircuitEvaluator eval = CircuitEvaluator.GetInstance();

            _outputModel = eval.InitFromModel(_model);
            OutputGrid.LoadModel(_model, _outputModel);
        }
예제 #10
0
        /// <summary>
        /// Translates Netlist object mode to SpiceSharp netlist.
        /// </summary>
        /// <param name="netlist">A object model of the netlist.</param>
        /// <returns>
        /// A new SpiceSharp netlist.
        /// </returns>
        public SpiceModel <SpiceSharp.Circuit, Simulation> Read(SpiceNetlist netlist)
        {
            if (netlist == null)
            {
                throw new System.ArgumentNullException(nameof(netlist));
            }

            // Get result netlist
            var result = new SpiceModel <Circuit, Simulation>(
                new Circuit(StringComparerProvider.Get(Settings.CaseSensitivity.IsEntityNameCaseSensitive)),
                netlist.Title);

            // Get reading context
            var resultService     = new ResultService(result);
            var nodeNameGenerator = new MainCircuitNodeNameGenerator(
                new [] { "0" },
                Settings.CaseSensitivity.IsNodeNameCaseSensitive);
            var            objectNameGenerator = new ObjectNameGenerator(string.Empty);
            INameGenerator nameGenerator       = new NameGenerator(nodeNameGenerator, objectNameGenerator);
            IRandomizer    randomizer          = new Randomizer(
                Settings.CaseSensitivity.IsDistributionNameCaseSensitive,
                seed: Settings.Seed);

            IExpressionParserFactory  expressionParserFactory  = new ExpressionParserFactory(Settings.CaseSensitivity);
            IExpressionFeaturesReader expressionFeaturesReader = new ExpressionFeaturesReader(expressionParserFactory);
            IExpressionValueProvider  expressionValueProvider  = new ExpressionValueProvider(expressionParserFactory);

            EvaluationContext expressionContext = new SpiceEvaluationContext(
                string.Empty,
                Settings.EvaluatorMode,
                Settings.CaseSensitivity,
                randomizer,
                expressionParserFactory,
                expressionFeaturesReader,
                expressionValueProvider,
                nameGenerator,
                resultService);

            var simulationEvaluationContexts = new SimulationEvaluationContexts(expressionContext);
            ISimulationPreparations simulationPreparations = new SimulationPreparations(
                new EntityUpdates(Settings.CaseSensitivity.IsParameterNameCaseSensitive, simulationEvaluationContexts),
                new SimulationsUpdates(simulationEvaluationContexts));

            ICircuitEvaluator      circuitEvaluator = new CircuitEvaluator(simulationEvaluationContexts, expressionContext);
            ISpiceStatementsReader statementsReader = new SpiceStatementsReader(Settings.Mappings.Controls,
                                                                                Settings.Mappings.Models, Settings.Mappings.Components);
            IWaveformReader waveformReader = new WaveformReader(Settings.Mappings.Waveforms);

            ICircuitContext circuitContext = new CircuitContext(
                "Root circuit context",
                null,
                circuitEvaluator,
                simulationPreparations,
                resultService,
                nameGenerator,
                statementsReader,
                waveformReader,
                Settings.CaseSensitivity,
                Settings.Mappings.Exporters,
                Settings.WorkingDirectory,
                null);

            // Set initial seed
            circuitContext.Evaluator.Seed = Settings.Seed;

            // Read statements form input netlist using created context
            circuitContext.Read(netlist.Statements, Settings.Orderer);

            // Set final seed
            result.Seed = circuitContext.Evaluator.Seed;

            return(result);
        }
예제 #11
0
        public string GenerateCode()
        {
            CircuitEvaluator eval  = CircuitEvaluator.GetInstance();
            ComputerModel    model = eval.Model;
            Dictionary <string, List <MethodCode> > methodsCodes = eval.GetMethodsCodes();

            StringBuilder builder = new StringBuilder();

            builder.AppendLine("using Quantum;");
            builder.AppendLine("using Quantum.Operations;");
            builder.AppendLine("using System;");
            builder.AppendLine("using System.Numerics;");
            builder.AppendLine("using System.Collections.Generic;");
            builder.AppendLine();
            builder.AppendLine("namespace QuantumConsole");
            builder.AppendLine("{");

            string extensions = GenerateCompositeExtensions(model, methodsCodes);

            if (!string.IsNullOrWhiteSpace(extensions))
            {
                builder.AppendLine(extensions);
            }

            builder.AppendLine("\tpublic class QuantumTest");
            builder.AppendLine("\t{");
            builder.AppendLine("\t\tpublic static void Main()");
            builder.AppendLine("\t\t{");
            builder.AppendLine("\t\t\tQuantumComputer comp = QuantumComputer.GetInstance();");

            string indent = "\t\t\t";

            foreach (RegisterModel reg in model.Registers)
            {
                builder.AppendLine(GenerateRegisterCode(reg, indent));
            }

            int rootDefPlace = builder.Length;

            _rootNeeded = false;

            string stepCode;

            for (int i = 0; i < model.Steps.Count; i++)
            {
                stepCode = GenerateStepCode(model, model.Steps[i], i, indent);
                builder.Append(stepCode);
            }
            if (_rootNeeded)
            {
                StringBuilder b = new StringBuilder();
                b.Append(indent).Append("Register root = comp.GetRootRegister(");
                b.Append(model.Registers[0].Name);
                for (int i = 1; i < model.Registers.Count; i++)
                {
                    RegisterModel reg = model.Registers[i];
                    b.Append(" ,").Append(reg.Name);
                }
                b.AppendLine(");");

                builder.Insert(rootDefPlace, b.ToString());
            }
            builder.AppendLine("\t\t}");
            builder.AppendLine("\t}");
            builder.AppendLine("}");

            return(builder.ToString());
        }
예제 #12
0
파일: HomeVM.cs 프로젝트: Wowand/quantum
        public void MakeComposite(object parameter)
        {
            try
            {
                List <Gate>          toGroup = _model.GetSelectedGates();
                CompositeInput       ci      = new CompositeInput();
                ICustomContentDialog dialog1 = _window.DialogManager
                                               .CreateCustomContentDialog(ci, DialogMode.OkCancel);
                dialog1.Ok = () =>
                {
                    try
                    {
                        string name = ci.nameBox.Text;

                        string pattern = @"^\s*[a-zA-Z_][a-zA-Z0-9_]*\s*$";
                        Regex  regex   = new Regex(pattern);
                        Match  match   = regex.Match(name);
                        if (!match.Success)
                        {
                            throw new Exception("Entered name is invalid.");
                        }

                        CircuitEvaluator eval = CircuitEvaluator.GetInstance();
                        Dictionary <string, List <MethodInfo> > dict = eval.GetExtensionGates();
                        if (dict.ContainsKey(name))
                        {
                            MessageBox.Show(
                                "Another composite gate with the same name already exist. Please choose other name.",
                                "New composite gate",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                        }
                        else
                        {
                            List <Gate> alreadyDefined = _model.FindComposite(name);
                            if (alreadyDefined != null)
                            {
                                MessageBox.Show(
                                    "Another composite gate with the same name already exist. Please choose other name.",
                                    "New composite gate",
                                    MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                            }
                            else
                            {
                                _model.MakeComposite(name, toGroup);

                                if (!_toolsVM.Contains(name))
                                {
                                    List <string> newTools = _toolsVM;
                                    newTools.Add(name);
                                    CompositeTools = newTools;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Unable to create composite gate from selection:\n" + ex.Message,
                                        "Unable to create composite gate",
                                        MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                    }
                };
                dialog1.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to create composite gate from selection:\n" + ex.Message,
                                "Unable to create composite gate",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
            }
        }