/*
* Redberry: symbolic tensor computations.
*
* Copyright (c) 2010-2012:
* Stanislav Poslavsky <stvlpos@mail.ru>
* Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
*
* This file is part of Redberry.
*
* Redberry is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Redberry is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Redberry. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.redberry.core.parser;
import java.util.ArrayList;
import java.util.List;
import cc.redberry.core.tensor.Integral;
import cc.redberry.core.tensor.SimpleTensor;
import cc.redberry.core.tensor.Tensor;
/**
*
* @author Dmitry Bolotin
* @author Stanislav Poslavsky
*/
public class ParserIntegral implements TensorParser {
public static final ParserIntegral INSTANCE = new ParserIntegral();
private final String iD = StringDefaults.get(Integral.class);
private final int iDlength = iD.length();
private ParserIntegral() {
}
private final static int parserID = 9001;
@Override
public int getPriority() {
return parserID;
}
@Override
public Tensor parse(String expression, Parser parser) {
char[] expressionChars = expression.toCharArray();
if (expressionChars.length < iDlength + 2)
return null;
if (!(expression.substring(0, iDlength).equals(iD) && expressionChars[iDlength] == '['
&& expressionChars[expressionChars.length - 1] == ']'))
return null;
char c;
int level = 0;
for (int i = 0; i < expressionChars.length; ++i) {
c = expressionChars[i];
if (c == '[')
level++;
if (c == ']') {
level--;
if (level == 0 && i != expressionChars.length - 1)
return null;
}
}
List<Tensor> tensors = new ArrayList<>();
StringBuilder sb = new StringBuilder();
level = 0;
for (int i = iDlength + 1; i < expressionChars.length - 1; ++i) {
c = expressionChars[i];
if (c == '(' || c == '[')
level++;
if (c == ')' || c == ']')
level--;
if (level < 0)
throw new BracketsError();
if (c == ',' && level == 0) {
tensors.add(parser.parse(sb.toString()));
sb = new StringBuilder();
} else
sb.append(c);
}
tensors.add(parser.parse(sb.toString()));
if (tensors.size() <= 1)
return null;
SimpleTensor[] vars = new SimpleTensor[tensors.size() - 1];
Tensor var;
for (int i = 1; i < tensors.size(); ++i) {
var = tensors.get(i);
if (!(var instanceof SimpleTensor))
return null;
vars[i - 1] = (SimpleTensor) var;
}
return new Integral(tensors.get(0), vars);
}
}