/// <summary> /// Permite efectuar a leitura de um polinómio a partir de texto. /// </summary> /// <remarks> /// Se a leitura não for bem sucedida, é lançada uma excep~ção. /// </remarks> /// <param name="polynomial">O texto.</param> /// <returns>O polinómio.</returns> public UnivariatePolynomialNormalForm <int> Read(string polynomial) { var integerDomain = new IntegerDomain(); var integerParser = new IntegerParser <string>(); var conversion = new ElementToElementConversion <int>(); var polInputReader = new StringReader(polynomial); var polSymbolReader = new StringSymbolReader(polInputReader, false); var polParser = new UnivariatePolynomialReader <int, CharSymbolReader <string> >( "x", integerParser, integerDomain); var result = default(UnivariatePolynomialNormalForm <int>); if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result)) { // O polinómio foi lido com sucesso. return(result); } else { // Não é possível ler o polinómio. throw new Exception("Can't read integer polynomial."); } }
/// <summary> /// Permite fazer a leitura de um vector a partir de texto. /// </summary> /// <param name="lines">O tamanho do vector.</param> /// <param name="vectorString">O texto que representa o vector.</param> /// <returns>O vector.</returns> public IMathVector <double> ReadVector(int length, string vectorString) { var integerParser = new DoubleExpressionParser(); var vectorFactory = new ArrayVectorFactory <double>(); var reader = new StringReader(vectorString); var stringSymbolReader = new StringSymbolReader(reader, false); var vectorReader = new ConfigVectorReader <double, string, string, CharSymbolReader <string> >( length, vectorFactory); vectorReader.MapInternalDelimiters("left_bracket", "right_bracket"); vectorReader.AddBlanckSymbolType("blancks"); vectorReader.SeparatorSymbType = "comma"; var vector = default(IMathVector <double>); if (vectorReader.TryParseVector(stringSymbolReader, integerParser, out vector)) { return(vector); } else { throw new Exception("An error has occured while reading integer vector."); } }
public IOdmpMatrixSet <ComponentType, LineType, ColumnType, T> Read( Stream stream, T defaultValue = default(T), IEqualityComparer <ComponentType> componentComparer = null, IEqualityComparer <LineType> lineComparer = null, IEqualityComparer <ColumnType> columnComparer = null) { this.defaultValue = defaultValue; this.componentComparer = componentComparer; this.lineComparer = lineComparer; this.columnComparer = columnComparer; this.coordState = 0; var reader = new StreamReader(stream); var symbolReader = new StringSymbolReader(reader, true); this.matrixSet.Clear(); var stateMachine = new StateMachine <string, string>( this.states[0], this.states[1]); stateMachine.RunMachine(symbolReader); return(this.matrixSet); }
/// <summary> /// Permite efectuar a leitura de um polinómio com coeficientes fraccionários a partir de texto. /// </summary> /// <remarks> /// Se a leitura não for bem sucedida, é lançada uma excep~ção. /// </remarks> /// <param name="polynomial">O texto.</param> /// <returns>O polinómio.</returns> public UnivariatePolynomialNormalForm <Fraction <BigInteger> > Read(string polynomial) { var integerDomain = new BigIntegerDomain(); var fractionField = new FractionField <BigInteger>(integerDomain); var integerParser = new BigIntegerParser <string>(); var fractionParser = new FieldDrivenExpressionParser <Fraction <BigInteger> >( new SimpleElementFractionParser <BigInteger>(integerParser, integerDomain), fractionField); var conversion = new IntegerBigIntFractionConversion(integerDomain, new BigIntegerToIntegerConversion()); var polInputReader = new StringReader(polynomial); var polSymbolReader = new StringSymbolReader(polInputReader, false); var polParser = new UnivariatePolynomialReader <Fraction <BigInteger>, CharSymbolReader <string> >( "x", fractionParser, fractionField); var result = default(UnivariatePolynomialNormalForm <Fraction <BigInteger> >); if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result)) { // O polinómio foi lido com sucesso. return(result); } else { // Não é possível ler o polinómio. throw new Exception("Can't read integer polynomial."); } }
/// <summary> /// Faz a leitura de uma matriz de valores numéricos. /// </summary> /// <param name="lines">The number of lines.</param> /// <param name="columns">The number of columns.</param> /// <param name="arrayString">O texto que representa a matriz.</param> /// <returns>A matriz lida.</returns> public ArrayMathMatrix <double> ReadArray(int lines, int columns, string arrayString) { var expressionParser = new DoubleExpressionParser(); var reader = new StringReader(arrayString); var stringSymbolReader = new StringSymbolReader(reader, false); var arrayMatrixFactory = new ArrayMathMatrixFactory <double>(); var arrayMatrixReader = new ConfigMatrixReader <double, IMathMatrix <double>, string, string>( lines, columns); arrayMatrixReader.MapInternalDelimiters("left_bracket", "right_bracket"); arrayMatrixReader.AddBlanckSymbolType("blancks"); arrayMatrixReader.SeparatorSymbType = "comma"; var matrix = default(IMathMatrix <double>); if (arrayMatrixReader.TryParseMatrix(stringSymbolReader, expressionParser, (i, j) => arrayMatrixFactory.CreateMatrix(i, j), out matrix)) { return(matrix as ArrayMathMatrix <double>); } else { throw new ArgumentException("Can't read the specified matrix."); } }
/// <summary> /// Permite fazer a leitura de um polinómio genérico a partir de uma reprsentação textual. /// </summary> /// <typeparam name="T">O tipo de dados associado aos coeficientes.</typeparam> /// <param name="polynomialRepresentation">A representação textual do polinómio.</param> /// <param name="polynomialRing">O anel responsável pelas operações sobre os coeficientes.</param> /// <param name="coeffsParser">O leitor de coeficientes.</param> /// <param name="conversion">O conversor entre inteiros e o tiop de coeficiente.</param> /// <param name="readNegativeNumbers"> /// Indica se os números negativos são para ser lidos ou se é lido /// o sinal e depois o respectivo valor como símbolos independentes.</param> /// <returns></returns> public static Polynomial <T> ReadPolynomial <T>( string polynomialRepresentation, IRing <T> polynomialRing, IConversion <int, T> conversion, IParse <T, string, string> coeffsParser, bool readNegativeNumbers = false) { var polInputReader = new StringReader(polynomialRepresentation); var polSymbolReader = new StringSymbolReader(polInputReader, readNegativeNumbers); var polParser = new PolynomialReader <T, CharSymbolReader <string> >( coeffsParser, polynomialRing); var result = default(Polynomial <T>); if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result)) { // O polinómio foi lido com sucesso. return(result); } else { // Não é possível ler o polinómio. throw new Exception("Can't read polynomial."); } }
/// <summary> /// Permite fazer a leitura de um vector. /// </summary> /// <typeparam name="T">O tipo de elementos do vector.</typeparam> /// <param name="dimension">A dimensão do vector a ser lido.</param> /// <param name="vectorText">O texto que representa o vector.</param> /// <param name="vectorFactory">A fábrica responsável pela criação de vectores.</param> /// <param name="elementParser">O leitor de elementos.</param> /// <param name="readNegativeNumbers">Indica se são lidos os números negativos.</param> /// <returns></returns> public static IMathVector <T> ReadVector <T>( int dimension, string vectorText, IMathVectorFactory <T> vectorFactory, IParse <T, string, string> elementParser, bool readNegativeNumbers = false) { var reader = new StringReader(vectorText); var stringSymbolReader = new StringSymbolReader(reader, readNegativeNumbers); var arrayVectorReader = new ConfigVectorReader <T, string, string, CharSymbolReader <string> >( dimension, vectorFactory); arrayVectorReader.MapInternalDelimiters("left_bracket", "right_bracket"); arrayVectorReader.AddBlanckSymbolType("blancks"); arrayVectorReader.SeparatorSymbType = "comma"; var vector = default(IMathVector <T>); if (arrayVectorReader.TryParseVector(stringSymbolReader, elementParser, out vector)) { return(vector); } else { throw new Exception("Can't read vector."); } }
/// <summary> /// Permite fazer a leitura de uma matriz. /// </summary> /// <typeparam name="T">O tipo de elementos na matriz.</typeparam> /// <param name="lines">O número de linhas.</param> /// <param name="columns">O número de colunas.</param> /// <param name="matrixText">A representação textual da matriz.</param> /// <param name="matrixFactory">A fábrica responsável pela criação de matrizes.</param> /// <param name="elementParser">O leitor de elementos.</param> /// <param name="readNegativeNumbers">Indica se são lidos os números negativos.</param> /// <returns>A matriz.</returns> public static M ReadMatrix <T, M>( int lines, int columns, string matrixText, Func <int, int, M> matrixFactory, IParse <T, string, string> elementParser, bool readNegativeNumbers = false) where M : IMatrix <T> { var reader = new StringReader(matrixText); var stringSymbolReader = new StringSymbolReader(reader, readNegativeNumbers); var arrayMatrixReader = new ConfigMatrixReader <T, M, string, string>( lines, columns); arrayMatrixReader.MapInternalDelimiters("left_bracket", "right_bracket"); arrayMatrixReader.AddBlanckSymbolType("blancks"); arrayMatrixReader.SeparatorSymbType = "comma"; var matrix = default(M); if (arrayMatrixReader.TryParseMatrix( stringSymbolReader, elementParser, matrixFactory, out matrix)) { return(matrix); } else { throw new Exception("Can't read matrix."); } }
/// <summary> /// Permit realizar a leitura de um polinómio com coeficientes fraccionários. /// </summary> /// <typeparam name="T">O tipo de dados dos componentes das fracções.</typeparam> /// <param name="polynomialRepresentation">A representação polinomial.</param> /// <param name="domain">O domínio responsável pelas operações sobre os elementos das fracções.</param> /// <param name="itemsParser">O leitor de elementos da fracção.</param> /// <param name="conversion">A conversão entre cada fracção e o valor inteiro.</param> /// <param name="variableName">O nome da variável.</param> /// <param name="readNegativeNumbers">Indica se são lidos os números negativos.</param> /// <returns>O polinómio lido.</returns> public static UnivariatePolynomialNormalForm <Fraction <T> > ReadFractionalCoeffsUnivarPol <T, D>( string polynomialRepresentation, D domain, IParse <T, string, string> itemsParser, IConversion <int, Fraction <T> > conversion, string variableName, bool readNegativeNumbers = false) where D : IEuclidenDomain <T> { var fractionField = new FractionField <T>(domain); var fractionParser = new FieldDrivenExpressionParser <Fraction <T> >( new SimpleElementFractionParser <T>(itemsParser, domain), fractionField); var polInputReader = new StringReader(polynomialRepresentation); var polSymbolReader = new StringSymbolReader(polInputReader, readNegativeNumbers); var polParser = new UnivariatePolynomialReader <Fraction <T>, CharSymbolReader <string> >( "x", fractionParser, fractionField); var result = default(UnivariatePolynomialNormalForm <Fraction <T> >); if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result)) { // O polinómio foi lido com sucesso. return(result); } else { // Não é possível ler o polinómio. throw new Exception("Can't read polynomial."); } }
/// <summary> /// Permite realizar a leitura de um polinómio a partir de uma representação textual. /// </summary> /// <typeparam name="T">O tipo dos coeficientes do polinómio.</typeparam> /// <param name="polynomialRepresentation">A representação textual do polinómio.</param> /// <param name="ring">O anel responsável pelas operações sobre os coeficientes.</param> /// <param name="coeffsParser">O leitor de representações textuais para os coeficientes.</param> /// <param name="conversion">A conversão do tipo do coeficientes para inteiro.</param> /// <param name="externalDelimitersTypes">Os delimitadores externos.</param> /// <param name="readNegativeNumbers">Indica se o leitor identifica números negativos.</param> /// <returns>O polinómio lido a partir da representação textual.</returns> public static Polynomial <T> ReadPolynomial <T>( string polynomialRepresentation, IRing <T> ring, IParse <T, string, string> coeffsParser, IConversion <int, T> conversion, Dictionary <string, string> externalDelimitersTypes, bool readNegativeNumbers = false) { var polInputReader = new StringReader(polynomialRepresentation); var polSymbolReader = new StringSymbolReader(polInputReader, readNegativeNumbers); var polParser = new PolynomialReader <T, CharSymbolReader <string> >( coeffsParser, ring); foreach (var kvp in externalDelimitersTypes) { polParser.RegisterExternalDelimiterTypes(kvp.Key, kvp.Value); } var result = default(Polynomial <T>); if (polParser.TryParsePolynomial(polSymbolReader, conversion, out result)) { // O polinómio foi lido com sucesso. return(result); } else { // Não é possível ler o polinómio. throw new Exception("Can't read polynomial."); } }
/// <summary> /// Perpara o leitor de símbolos a partir de um leitor de texto. /// </summary> /// <param name="reader">O leitor de texto.</param> /// <returns>O leitor de símbolos.</returns> private StringSymbolReader PrepareSymbolReader(TextReader reader) { var result = new StringSymbolReader(reader, false); result.RegisterKeyWordType("while", "while"); result.RegisterKeyWordType("if", "if"); result.RegisterKeyWordType("for", "for"); result.RegisterKeyWordType("else", "else"); result.RegisterKeyWordType("true", "boolean"); result.RegisterKeyWordType("false", "boolean"); return(result); }
public void RunTest_TabularItem() { var csvStringBuilder = new StringBuilder(); csvStringBuilder.AppendLine("12, 9,7,6,4"); csvStringBuilder.AppendLine("12,11,8,7,5"); csvStringBuilder.AppendLine("13,10,9,6,3"); csvStringBuilder.Append("12,8,6,4,2"); var csvString = csvStringBuilder.ToString(); var csvStringReader = new StringReader(csvString); var parser = new IntegerParser <string>(); var csvParser = new CsvFileParser <ITabularItem, int, string, string>( "new_line", "comma", (i, j) => parser); csvParser.AddIgnoreType("space"); csvParser.AddIgnoreType("carriage_return"); var csvSymbolReader = new StringSymbolReader(csvStringReader, true, false); var adder = new TabularItemAdder <int>(); var tabularItem = new TabularListsItem(); csvParser.Parse(csvSymbolReader, tabularItem, adder); var integerDomain = new IntegerDomain(); var numberTdecomposition = new IntegerMinWeightTdecomposition <int>( Comparer <int> .Default, integerDomain); var result = numberTdecomposition.Run(18, tabularItem); var expectedMedians = new List <int>() { 3, 5, 5, 5 }; Assert.AreEqual(17, result.Cost); CollectionAssert.AreEquivalent(expectedMedians, result.Medians.ToList()); }
/// <summary> /// Realiza a leitura. /// </summary> /// <remarks> /// Se a leitura não for bem-sucedida, os erros de leitura serão registados no diário /// e será retornado o objecto por defeito. /// </remarks> /// <param name="symbolListToParse">O vector de símbolos a ser lido.</param> /// <param name="errorLogs">O objecto que irá manter o registo do diário da leitura.</param> /// <returns>O valor lido.</returns> public AMathematicsObject Parse( ISymbol <string, string>[] symbolListToParse, ILogStatus <string, EParseErrorLevel> errorLogs) { var valueReader = new StringReader(symbolListToParse[0].SymbolValue); var symbolReader = new StringSymbolReader(valueReader, true); this.IgnoreVoids(symbolReader); var readed = symbolReader.Peek(); if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.EOF)) { return(new EmptyMathematicsObject()); } else if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.LEFT_PARENTHESIS)) { } else if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.LEFT_BRACKET)) { } else if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.INTEGER)) { return(new IntegerMathematicsObject() { Value = int.Parse(symbolListToParse[0].SymbolValue) }); } else if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.DOUBLE)) { return(new DoubleMathematicsObject() { Value = double.Parse( symbolListToParse[0].SymbolValue, CultureInfo.InvariantCulture.NumberFormat) }); } else if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.STRING)) { return(new NameMathematicsObject(symbolListToParse[0].SymbolValue, this.mediator)); } else if (readed.SymbolType == Utils.GetStringSymbolType(EStringSymbolReaderType.DOUBLE_QUOTE)) { return(new StringMathematicsObject() { Value = symbolListToParse[0].SymbolValue }); } else if (readed.SymbolType == "boolean") { return(new BooleanMathematicsObject() { Value = bool.Parse(symbolListToParse[0].SymbolValue) }); } else { return(null); } var lispStyleListParser = LispStyleList <AMathematicsObject> .GetParser(this); var rangeReader = new RangeNoConfigReader <AMathematicsObject, string, string>(); var multidimensionalRangeParser = new MultiDimensionalRangeReader <AMathematicsObject, string, string>(rangeReader); var multidimensionalRange = default(MultiDimensionalRange <AMathematicsObject>); var parsed = multidimensionalRangeParser.TryParseRange( symbolReader, this, out multidimensionalRange); throw new NotImplementedException(); }
/// <summary> /// Função de transição inicial - estado 0. /// </summary> /// <param name="reader">O leitor de símbolos.</param> /// <returns>O próximo estado.</returns> private IState <string, string> StartTransition(ISymbolReader <string, string> reader) { var readed = reader.Get(); var topScopeDefinition = this.scopeDefinitionStack.Pop(); if (readed.SymbolType == "eof") { if (!string.IsNullOrEmpty(this.currentItem)) { var symbolReader = new StringSymbolReader(new StringReader(this.currentItem), false); this.lastExpressionResult = this.expressionReader.Parse(symbolReader); this.currentItem = string.Empty; if (this.lastExpressionResult.IsFunctionObject) { ((AMathematicsFunctionObject)this.lastExpressionResult).Evaulate(); } } if (topScopeDefinition.ScopeType != EScopeType.MAIN) { this.currentResult.InterpreterMessageStatus = EMathematicsInterpreterStatus.WAITING; this.currentResult.InterpreterResultMessage = "Sentence is incomplete. Scope delimiters don't match."; if (topScopeDefinition.ScopeType == EScopeType.WHILE) { var whileCondition = topScopeDefinition.ConditionExpression; if (whileCondition.AssertCondition()) { (reader as StringSymbolReader).RestoreToMemento(topScopeDefinition.ScopeStartMemento); } } else if (topScopeDefinition.ScopeType == EScopeType.FOR) { var updateExpression = topScopeDefinition.UpdateExpression; updateExpression.Evaulate(); var forCondition = topScopeDefinition.ConditionExpression; if (forCondition.AssertCondition()) { (reader as StringSymbolReader).RestoreToMemento(topScopeDefinition.ScopeStartMemento); } } this.scopeDefinitionStack.Push(topScopeDefinition); return(this.stateList[1]); } else { this.currentResult.InterpreterMessageStatus = EMathematicsInterpreterStatus.COMPLETED; this.currentResult.InterpreterResultMessage = this.lastExpressionResult.ToString(); return(this.stateList[1]); } } else if (readed.SymbolType == "semi_colon") { var symbolReader = new StringSymbolReader(new StringReader(this.currentItem), false); this.lastExpressionResult = this.expressionReader.Parse(symbolReader); this.currentItem = string.Empty; if (this.lastExpressionResult.IsFunctionObject) { ((AMathematicsFunctionObject)this.lastExpressionResult).Evaulate(); } if (topScopeDefinition.ScopeType == EScopeType.WHILE) { var whileCondition = topScopeDefinition.ConditionExpression; if (whileCondition.AssertCondition()) { (reader as StringSymbolReader).RestoreToMemento(topScopeDefinition.ScopeStartMemento); } } else if (topScopeDefinition.ScopeType == EScopeType.FOR) { var updateExpression = topScopeDefinition.UpdateExpression; updateExpression.Evaulate(); var forCondition = topScopeDefinition.ConditionExpression; if (forCondition.AssertCondition()) { (reader as StringSymbolReader).RestoreToMemento(topScopeDefinition.ScopeStartMemento); } } this.scopeDefinitionStack.Push(topScopeDefinition); } else if (readed.SymbolType == "left_brace") { var innerScope = new ScopeDefinition() { ScopeType = EScopeType.INNER }; this.scopeDefinitionStack.Push(topScopeDefinition); this.scopeDefinitionStack.Push(innerScope); } else if (readed.SymbolType == "right_brace") { if (topScopeDefinition.ScopeType == EScopeType.MAIN) { return(this.SetupErrorAndQuit("Scope delimiters don't match.")); } else if (topScopeDefinition.ScopeType == EScopeType.INNER) { return(this.stateList[0]); } else if (topScopeDefinition.ScopeType == EScopeType.WHILE) { var whileCondition = topScopeDefinition.ConditionExpression; if (whileCondition.AssertCondition()) { (reader as StringSymbolReader).RestoreToMemento(topScopeDefinition.ScopeStartMemento); this.scopeDefinitionStack.Push(topScopeDefinition); } } else if (topScopeDefinition.ScopeType == EScopeType.FOR) { var updateExpression = topScopeDefinition.UpdateExpression; updateExpression.Evaulate(); var forCondition = topScopeDefinition.ConditionExpression; if (forCondition.AssertCondition()) { (reader as StringSymbolReader).RestoreToMemento(topScopeDefinition.ScopeStartMemento); this.scopeDefinitionStack.Push(topScopeDefinition); } } } else if (readed.SymbolType == "while") { this.scopeDefinitionStack.Push(topScopeDefinition); this.scopeDefinitionStack.Push(new ScopeDefinition() { ScopeType = EScopeType.WHILE }); return(this.stateList[5]); } else if (readed.SymbolType == "if") { this.scopeDefinitionStack.Push(topScopeDefinition); this.scopeDefinitionStack.Push(new ScopeDefinition() { ScopeType = EScopeType.IF_ELSE }); return(this.stateList[5]); } else if (readed.SymbolType == "for") { this.scopeDefinitionStack.Push(topScopeDefinition); this.scopeDefinitionStack.Push(new ScopeDefinition() { ScopeType = EScopeType.FOR }); return(this.stateList[7]); } else if (readed.SymbolType == "else") { this.scopeDefinitionStack.Push(topScopeDefinition); return(this.SetupErrorAndQuit("Unexpected word else.")); } else { this.scopeDefinitionStack.Push(topScopeDefinition); this.currentItem += readed.SymbolValue; } return(this.stateList[0]); }