use of org.matheclipse.core.interfaces.IAssociation in project symja_android_library by axkr.
the class SerializableTest method testAssociation.
public void testAssociation() {
IAssociation assoc = F.assoc(F.List(F.Rule(F.a, F.b)));
equalsCopy(assoc);
}
use of org.matheclipse.core.interfaces.IAssociation in project symja_android_library by axkr.
the class AbstractAST method evaluate.
/**
* {@inheritDoc}
*/
@Override
public IExpr evaluate(EvalEngine engine) {
LOGGER.debug("Evaluate {}", this);
final IExpr head = head();
final int argSize = argSize();
if (head instanceof ISymbol) {
ISymbol headSymbol = (ISymbol) head;
Class<?> clazz = headSymbol.getContext().getJavaClass();
if (clazz != null) {
String staticMethodName = headSymbol.getSymbolName();
// try {
// Method method = clazz.getMethod(staticMethodName);
// if (Modifier.isStatic(method.getModifiers())) {
// Parameter[] parameters = method.getParameters();
// if (parameters.length == argSize()) {
// Object[] params = JavaFunctions.determineParameters(this, parameters, 1);
// if (params != null) {
// Object result;
// try {
// result = method.invoke(null, params);
// if (result instanceof String) {
// return F.stringx((String) result);
// }
// return Object2Expr.convert(result);
// } catch (IllegalAccessException
// | IllegalArgumentException
// | InvocationTargetException e) {
// // fall through?
// }
// }
// }
// }
//
// } catch (IllegalArgumentException | NoSuchMethodException | SecurityException e) {
// // fall through?
// }
Method[] methods = clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
if (Modifier.isStatic(methods[i].getModifiers())) {
if (staticMethodName.equals(methods[i].getName())) {
Parameter[] parameters = methods[i].getParameters();
if (parameters.length == argSize()) {
Object[] params = JavaFunctions.determineParameters(this, parameters, 1);
if (params != null) {
Object result;
try {
result = methods[i].invoke(null, params);
if (result instanceof String) {
return F.stringx((String) result);
}
return Object2Expr.convert(result, false, true);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// fall through?
}
}
}
}
}
}
}
if (head instanceof IBuiltInSymbol) {
final IEvaluator evaluator = ((IBuiltInSymbol) head).getEvaluator();
if (evaluator instanceof ICoreFunctionEvaluator) {
try {
ICoreFunctionEvaluator functionEvaluator = (ICoreFunctionEvaluator) evaluator;
EvalEngine.OptionsResult opres = engine.checkBuiltinArguments(this, functionEvaluator);
if (opres == null) {
return F.NIL;
}
IAST ast = opres.result;
IBuiltInSymbol header = ((IBuiltInSymbol) head);
if ((header.getAttributes() & ISymbol.SEQUENCEHOLD) != ISymbol.SEQUENCEHOLD) {
IExpr temp;
if ((temp = F.flattenSequence(this)).isPresent()) {
return temp;
}
}
if (isBooleanFunction()) {
IExpr temp = extractConditionalExpression(false);
if (temp.isPresent()) {
return temp;
}
}
IExpr evaluateTemp = evalEvaluate(engine);
if (evaluateTemp.isPresent()) {
return evaluateTemp;
}
return functionEvaluator.evaluate(ast, engine);
} catch (ValidateException ve) {
return IOFunctions.printMessage(topHead(), ve, engine);
} catch (FlowControlException e) {
throw e;
} catch (SymjaMathException ve) {
LOGGER.log(engine.getLogLevel(), topHead(), ve);
return F.NIL;
}
}
}
}
if (head.isAssociation() && argSize == 1) {
return ((IAssociation) head).getValue(arg1());
}
final ISymbol symbol = topHead();
IExpr temp = engine.evalAttributes(symbol, this);
if (temp.isPresent()) {
return temp;
}
return engine.evalRules(symbol, this);
}
use of org.matheclipse.core.interfaces.IAssociation in project symja_android_library by axkr.
the class OutputFormFactory method convert.
private void convert(final Appendable buf, final IExpr o, final int precedence, boolean isASTHead) throws IOException {
if (o instanceof IAST) {
final IAST list = (IAST) o;
if (!list.isPresent()) {
append(buf, "NIL");
return;
}
if (o.isDataset()) {
// TODO improve output
buf.append(o.toString());
return;
} else if (o.isAssociation()) {
convertAssociation(buf, (IAssociation) o);
return;
} else if (o.isAST(S.Association, 1)) {
buf.append("<||>");
return;
}
IExpr header = list.head();
if (!header.isSymbol()) {
// print expressions like: f(#1, y)& [x]
IAST[] derivStruct = list.isDerivativeAST1();
if (derivStruct != null) {
IAST a1Head = derivStruct[0];
IAST headAST = derivStruct[1];
if (a1Head.isAST1() && a1Head.arg1().isInteger() && headAST.isAST1() && (headAST.arg1().isSymbol() || headAST.arg1().isAST()) && derivStruct[2] != null) {
try {
int n = ((IInteger) a1Head.arg1()).toInt();
if (n == 1 || n == 2) {
IExpr symbolOrAST = headAST.arg1();
convert(buf, symbolOrAST, Integer.MIN_VALUE, false);
if (n == 1) {
append(buf, "'");
} else if (n == 2) {
append(buf, "''");
}
convertArgs(buf, symbolOrAST, list);
return;
}
} catch (ArithmeticException ae) {
}
}
}
convert(buf, header, Integer.MIN_VALUE, true);
// avoid fast StackOverflow
append(buf, "[");
for (int i = 1; i < list.size(); i++) {
convert(buf, list.get(i), Integer.MIN_VALUE, false);
if (i < list.argSize()) {
append(buf, ",");
}
}
append(buf, "]");
return;
}
if (header.isSymbol()) {
ISymbol head = (ISymbol) header;
int functionID = head.ordinal();
if (functionID > ID.UNKNOWN) {
switch(functionID) {
case ID.TwoWayRule:
case ID.UndirectedEdge:
if (list.isAST2()) {
convert(buf, list.arg1(), Integer.MIN_VALUE, false);
buf.append("<->");
convert(buf, list.arg2(), Integer.MIN_VALUE, false);
return;
}
break;
case ID.DirectedEdge:
if (list.isAST2()) {
convert(buf, list.arg1(), Integer.MIN_VALUE, false);
buf.append("->");
convert(buf, list.arg2(), Integer.MIN_VALUE, false);
return;
}
break;
}
}
final Operator operator = getOperator(head);
if (operator != null) {
if (operator instanceof PostfixOperator) {
if (list.isAST1()) {
convertPostfixOperator(buf, list, (PostfixOperator) operator, precedence);
return;
}
} else {
if (convertOperator(operator, list, buf, isASTHead ? Integer.MAX_VALUE : precedence, head)) {
return;
}
}
}
if (functionID > ID.UNKNOWN) {
switch(functionID) {
case ID.Inequality:
if (list.size() > 3 && convertInequality(buf, list, precedence)) {
return;
}
break;
case ID.Quantity:
// if (head.equals(F.SeriesData) && (list.size() == 7)) {
if (list instanceof IQuantity) {
if (convertQuantityData(buf, (IQuantity) list, precedence)) {
return;
}
}
break;
case ID.SeriesData:
// if (head.equals(F.SeriesData) && (list.size() == 7)) {
if (list instanceof ASTSeriesData) {
if (convertSeriesData(buf, (ASTSeriesData) list, precedence)) {
return;
}
}
break;
case ID.SparseArray:
if (list.isSparseArray()) {
buf.append(list.toString());
return;
}
break;
case ID.Parenthesis:
convertArgs(buf, S.Parenthesis, list);
return;
case ID.List:
convertList(buf, list, false);
return;
case ID.MatrixForm:
if (list.isASTOrAssociation() && list.size() > 1) {
// see also MatrixForm in MathML or TeX format for "graphical representation".
IExpr normal = list.arg1().normal(false);
if (normal.isList()) {
// && normal.isMatrix() != null) {
IntList dims = LinearAlgebra.dimensions((IAST) normal, S.List);
convertList(buf, (IAST) normal, dims.size() >= 2);
return;
}
convert(buf, normal, Integer.MIN_VALUE, false);
return;
}
break;
case ID.Out:
if (list.isAST1() && list.arg1().isInteger()) {
int lineNumber = list.arg1().toIntDefault();
if (lineNumber == -1) {
buf.append("%");
return;
} else if (lineNumber == -2) {
buf.append("%%");
return;
}
}
break;
case ID.Part:
if (list.size() >= 3) {
convertPart(buf, list);
return;
}
break;
case ID.Slot:
if (list.isAST1() && list.arg1().isInteger()) {
convertSlot(buf, list);
return;
}
break;
case ID.SlotSequence:
if (list.isAST1() && list.arg1().isInteger()) {
convertSlotSequence(buf, list);
return;
}
break;
case ID.Defer:
case ID.HoldForm:
if (list.isAST1()) {
convert(buf, list.arg1(), Integer.MIN_VALUE, false);
return;
}
break;
case ID.DirectedInfinity:
if (list.isDirectedInfinity()) {
// head.equals(F.DirectedInfinity))
if (list.isAST0()) {
append(buf, "ComplexInfinity");
return;
}
if (list.isAST1()) {
if (list.arg1().isOne()) {
append(buf, "Infinity");
return;
} else if (list.arg1().isMinusOne()) {
if (Precedence.PLUS < precedence) {
append(buf, "(");
}
append(buf, "-Infinity");
if (Precedence.PLUS < precedence) {
append(buf, ")");
}
return;
} else if (list.arg1().isImaginaryUnit()) {
append(buf, "I*Infinity");
return;
} else if (list.arg1().isNegativeImaginaryUnit()) {
append(buf, "-I*Infinity");
return;
}
}
}
break;
case ID.Optional:
if (list.isAST2() && (list.arg1().isBlank() || list.arg1().isPattern())) {
convert(buf, list.arg1(), Integer.MIN_VALUE, false);
buf.append(":");
convert(buf, list.arg2(), Integer.MIN_VALUE, false);
return;
}
break;
case ID.Complex:
if (list.isAST2()) {
// used for visual comparison of steps
boolean isZeroRealPart = list.arg1().isZero();
final int prec = isZeroRealPart ? Precedence.TIMES : Precedence.PLUS;
if (prec < precedence) {
append(buf, "(");
}
if (isZeroRealPart) {
buf.append("I*");
convert(buf, list.arg2(), Precedence.TIMES, false);
} else {
convert(buf, list.arg1(), Precedence.PLUS, false);
buf.append("+I*");
convert(buf, list.arg2(), Precedence.TIMES, false);
}
if (prec < precedence) {
append(buf, ")");
}
return;
}
break;
case ID.Rational:
if (list.isAST2()) {
// used for visual comparison of steps
IExpr numerator = list.arg1();
final boolean isNegative = numerator.isNegative();
final int prec = isNegative ? Precedence.PLUS : Precedence.TIMES;
if (prec < precedence) {
append(buf, "(");
}
convert(buf, list.arg1(), Precedence.DIVIDE, false);
buf.append("/");
convert(buf, list.arg2(), Precedence.DIVIDE, false);
if (prec < precedence) {
append(buf, ")");
}
return;
}
break;
}
} else {
if (list instanceof ASTRealVector || list instanceof ASTRealMatrix) {
convertList(buf, list, false);
return;
}
}
}
convertAST(buf, list);
} else if (o instanceof ISignedNumber) {
convertNumber(buf, (ISignedNumber) o, precedence, NO_PLUS_CALL);
} else if (o instanceof IComplexNum) {
convertDoubleComplex(buf, (IComplexNum) o, precedence, NO_PLUS_CALL);
} else if (o instanceof IComplex) {
convertComplex(buf, (IComplex) o, precedence, NO_PLUS_CALL);
} else if (o instanceof ISymbol) {
convertSymbol(buf, (ISymbol) o);
} else if (o instanceof IPatternObject) {
convertPattern(buf, (IPatternObject) o);
} else if (o instanceof IStringX) {
convertString(buf, ((IStringX) o).toString());
} else {
convertString(buf, o.toString());
}
}
use of org.matheclipse.core.interfaces.IAssociation in project symja_android_library by axkr.
the class PatternMatcher method matchASTSpecialBuiltIn.
/**
* Test first if <code>functionID = lhsPatternAST.headID()</code> is a special pattern-matching
* construct (i.e. <code>
* Association, HoldPattern, Literal, Condition, Alternatives, Except, Complex, Rational, Optional, PatternTest, Verbatim
* </code>). If <code>true</code> evaluate the special pattern-matching construct otherwise
* continue with <code>lhsPatternAST</code> pattern matching.
*
* @param lhsPatternAST left-hand-side pattern AST
* @param lhsEvalExpr left-hand-side expression which should be matched by the pattern expression
* @param engine the evaluation engine
* @param stackMatcher a stack matcher
* @return
*/
private boolean matchASTSpecialBuiltIn(IAST lhsPatternAST, final IExpr lhsEvalExpr, EvalEngine engine, StackMatcher stackMatcher) {
int functionID = lhsPatternAST.headID();
if (functionID >= ID.Association && functionID <= ID.Verbatim) {
boolean matched = false;
if (lhsPatternAST.size() == 2) {
final IExpr[] patternValues;
switch(functionID) {
case ID.Association:
patternValues = fPatternMap.copyPattern();
try {
if (lhsEvalExpr.isAssociation()) {
IAST lhsPatternAssociation = lhsPatternAST;
// TODO set/determine pattern matching flags?
IASTMutable lhsPatternList = (IASTMutable) lhsPatternAssociation.normal(false);
lhsPatternList.set(0, S.Association);
IAssociation lhsEvalAssociation = (IAssociation) lhsEvalExpr;
IASTMutable lhsEvalList = lhsEvalAssociation.normal(false);
lhsEvalList.set(0, S.Association);
matched = matchExpr(lhsPatternList, lhsEvalList, engine, stackMatcher);
return matched;
}
matched = matchASTExpr(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
return matched;
case ID.Except:
patternValues = fPatternMap.copyPattern();
try {
matched = !matchExpr(lhsPatternAST.arg1(), lhsEvalExpr, engine, stackMatcher);
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
return matched;
case ID.HoldPattern:
case ID.Literal:
patternValues = fPatternMap.copyPattern();
try {
matched = matchExpr(lhsPatternAST.arg1(), lhsEvalExpr, engine, stackMatcher);
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
return matched;
case ID.Optional:
return matchOptional(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
case ID.Verbatim:
return lhsPatternAST.arg1().equals(lhsEvalExpr);
default:
}
} else if (lhsPatternAST.size() == 3) {
if (functionID >= ID.Complex && functionID <= ID.Rational) {
final IExpr[] patternValues;
switch(functionID) {
case ID.Complex:
patternValues = fPatternMap.copyPattern();
try {
if (lhsEvalExpr.isNumber()) {
INumber number = (INumber) lhsEvalExpr;
matched = matchExpr(lhsPatternAST.arg1(), number.re(), engine, stackMatcher) && matchExpr(lhsPatternAST.arg2(), number.im(), engine, stackMatcher);
return matched;
}
matched = matchASTExpr(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
return matched;
case ID.Condition:
return matchCondition(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
case ID.Except:
patternValues = fPatternMap.copyPattern();
try {
matched = !matchExpr(lhsPatternAST.arg1(), lhsEvalExpr, engine, stackMatcher) && matchExpr(lhsPatternAST.arg2(), lhsEvalExpr, engine, stackMatcher);
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
return matched;
case ID.Optional:
return matchOptional(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
case ID.PatternTest:
patternValues = fPatternMap.copyPattern();
try {
final IExpr lhsPatternExpr = lhsPatternAST.arg1();
final IExpr patternTest = lhsPatternAST.arg2();
if (lhsPatternExpr instanceof IPatternObject && patternTest.isFreeOfPatterns()) {
// other pattern symbol
if (matchPattern((IPatternObject) lhsPatternExpr, lhsEvalExpr, engine, stackMatcher)) {
if (fPatternMap.isPatternTest(lhsPatternExpr, patternTest, engine)) {
matched = stackMatcher.matchRest();
}
}
} else if (matchExpr(lhsPatternExpr, lhsEvalExpr, engine, stackMatcher)) {
matched = fPatternMap.isPatternTest(lhsPatternExpr, patternTest, engine);
}
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
return matched;
case ID.Rational:
patternValues = fPatternMap.copyPattern();
try {
// check for fractions (and no integers) here to be compatible with MMA
if (lhsEvalExpr.isFraction()) {
IFraction rational = (IFraction) lhsEvalExpr;
matched = matchExpr(lhsPatternAST.arg1(), rational.numerator(), engine, stackMatcher) && matchExpr(lhsPatternAST.arg2(), rational.denominator(), engine, stackMatcher);
return matched;
}
matched = matchASTExpr(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
return matched;
} finally {
if (!matched) {
fPatternMap.resetPattern(patternValues);
}
}
default:
}
}
}
} else {
if (lhsPatternAST.isAlternatives()) {
return matchAlternatives(lhsPatternAST, lhsEvalExpr, engine);
}
}
return matchASTExpr(lhsPatternAST, lhsEvalExpr, engine, stackMatcher);
}
use of org.matheclipse.core.interfaces.IAssociation in project symja_android_library by axkr.
the class ASTDataset method newListOfAssociations.
/**
* Create a <code>Dataset</code> object from a <code>List(...)</code> of associations. Each
* association represents a row in the <code>Dataset</code>. The left-hand-side of each singular
* rule in an association was assumed to be the name of the resulting dataset columns. Identical
* names maps the right-hand-side values of the rule to the same columns in the resulting <code>
* Dataset
* </code>.
*
* @param listOfAssociations
* @return {@link F#NIL} if the <code>Dataset</code> cannot be created
*/
public static IExpr newListOfAssociations(IAST listOfAssociations) {
// 1. phase: build up column names
List<String> colNames = new ArrayList<String>();
Set<String> colNamesSet = new HashSet<String>();
for (int i = 1; i < listOfAssociations.size(); i++) {
IAssociation assoc = (IAssociation) listOfAssociations.get(i);
for (int j = 1; j < assoc.size(); j++) {
IAST rule = assoc.getRule(j);
String columnName = rule.first().toString();
if (!colNamesSet.contains(columnName)) {
colNamesSet.add(columnName);
colNames.add(columnName);
}
}
}
if (colNames.size() > 0) {
// 2. phase: define the columns
Table table = Table.create();
Column<?>[] cols = new Column<?>[colNames.size()];
for (int i = 0; i < colNames.size(); i++) {
cols[i] = ExprColumn.create(colNames.get(i));
}
table.addColumns(cols);
// 3. phase: add the values
for (int i = 1; i < listOfAssociations.size(); i++) {
IAssociation assoc = (IAssociation) listOfAssociations.get(i);
Row row = table.appendRow();
for (int j = 1; j < assoc.size(); j++) {
IAST rule = assoc.getRule(j);
String columnName = rule.first().toString();
IExpr value = rule.second();
row.setExpr(columnName, value);
}
}
return newTablesawTable(table);
}
return F.NIL;
}
Aggregations