Search in sources :

Example 11 with Fun

use of suite.util.FunUtil.Fun in project suite by stupidsing.

the class FltFunUtil method suck.

/**
 * Sucks data from a sink and produce into a source.
 */
public static FltSource suck(Sink<FltSink> fun) {
    NullableSyncQueue<Float> queue = new NullableSyncQueue<>();
    FltSink enqueue = c -> enqueue(queue, c);
    Thread thread = Thread_.startThread(() -> {
        try {
            fun.sink(enqueue);
        } finally {
            enqueue(queue, EMPTYVALUE);
        }
    });
    return () -> {
        try {
            return queue.take();
        } catch (InterruptedException ex) {
            thread.interrupt();
            return Fail.t(ex);
        }
    };
}
Also used : Iterator(java.util.Iterator) LogUtil(suite.os.LogUtil) Source2(suite.util.FunUtil2.Source2) FltSink(suite.primitive.FltPrimitives.FltSink) Source(suite.util.FunUtil.Source) NullableSyncQueue(suite.util.NullableSyncQueue) Thread_(suite.util.Thread_) Fun(suite.util.FunUtil.Fun) Flt_Obj(suite.primitive.FltPrimitives.Flt_Obj) FltObjPair(suite.primitive.adt.pair.FltObjPair) FltObjSource(suite.primitive.FltPrimitives.FltObjSource) Sink(suite.util.FunUtil.Sink) FltTest(suite.primitive.FltPrimitives.FltTest) Collections(java.util.Collections) FltSource(suite.primitive.FltPrimitives.FltSource) Fail(suite.util.Fail) NullableSyncQueue(suite.util.NullableSyncQueue) FltSink(suite.primitive.FltPrimitives.FltSink)

Example 12 with Fun

use of suite.util.FunUtil.Fun in project suite by stupidsing.

the class BackTestMain method run.

@Override
protected boolean run(String[] args) {
    // BEGIN
    // END
    String arg0 = 0 < args.length ? args[0] : "";
    String arg1 = 1 < args.length ? args[1] : "";
    String arg2 = 2 < args.length ? args[2] : "";
    Streamlet<String> strategyMatches = !arg0.isEmpty() ? Read.from(arg0.split(",")) : null;
    Streamlet<Integer> years = !arg1.isEmpty() ? // 
    Read.from(// 
    arg1.split(",")).concatMap(s -> {
        Pair<String, String> pair = ParseUtil.search(s, "-", Assoc.RIGHT);
        return // 
        pair != null ? // 
        Ints_.range(Integer.valueOf(pair.t0), Integer.valueOf(pair.t1)).map(i -> i) : Read.each(Integer.valueOf(s));
    }) : // 
    Ints_.range(2007, Trade_.thisYear).map(i -> i);
    Fun<Time, Streamlet<Asset>> fun = // 
    !arg2.isEmpty() ? // 
    time -> Read.from(arg2.split(",")).map(cfg::queryCompany).collect(As::streamlet) : cfg::queryCompaniesByMarketCap;
    BackAllocConfigurations bac_ = new BackAllocConfigurations(cfg, fun);
    Streamlet2<String, BackAllocConfiguration> bacByTag = bac_.bacs().bacByName;
    Streamlet2<String, Simulate> simulationByKey = // 
    bacByTag.filterKey(// 
    n -> strategyMatches == null || strategyMatches.isAny(sm -> Wildcard.match(sm, n) != null)).map(// 
    Pair::of).join2(// 
    years.sort(Object_::compare).map(TimeRange::ofYear)).map2((pair, period) -> pair.t0, (pair, period) -> {
        BackAllocConfiguration bac = pair.t1;
        Streamlet<Asset> assets = bac.assetsFun.apply(period.from);
        return runner.backTest(bac.backAllocator, period, assets);
    }).collect(As::streamlet2);
    String content0 = // 
    Read.bytes(// 
    Paths.get("src/main/java/" + getClass().getName().replace('.', '/') + ".java")).collect(// 
    As::utf8decode).map(// 
    Chars::toString).collect(As::joined);
    String content1 = ParseUtil.fit(content0, "// BEGIN", "// END")[1];
    System.out.println(content1);
    System.out.println(runner.conclude(simulationByKey));
    return true;
}
Also used : Read(suite.streamlet.Read) Streamlet2(suite.streamlet.Streamlet2) Object_(suite.util.Object_) Trade_(suite.trade.Trade_) ExecutableProgram(suite.util.RunUtil.ExecutableProgram) Chars(suite.primitive.Chars) Fun(suite.util.FunUtil.Fun) RunUtil(suite.util.RunUtil) Wildcard(suite.parser.Wildcard) ParseUtil(suite.util.ParseUtil) Pair(suite.adt.pair.Pair) ConfigurationImpl(suite.trade.data.ConfigurationImpl) BackAllocConfiguration(suite.trade.backalloc.BackAllocConfiguration) Streamlet(suite.streamlet.Streamlet) Time(suite.trade.Time) BackAllocConfigurations(suite.trade.backalloc.BackAllocConfigurations) Paths(java.nio.file.Paths) Configuration(suite.trade.data.Configuration) As(suite.streamlet.As) Simulate(suite.trade.backalloc.BackAllocTester.Simulate) Ints_(suite.primitive.Ints_) Asset(suite.trade.Asset) Assoc(suite.node.io.Operator.Assoc) TimeRange(suite.trade.TimeRange) Time(suite.trade.Time) Object_(suite.util.Object_) As(suite.streamlet.As) Simulate(suite.trade.backalloc.BackAllocTester.Simulate) BackAllocConfigurations(suite.trade.backalloc.BackAllocConfigurations) Streamlet(suite.streamlet.Streamlet) BackAllocConfiguration(suite.trade.backalloc.BackAllocConfiguration) Pair(suite.adt.pair.Pair)

Example 13 with Fun

use of suite.util.FunUtil.Fun in project suite by stupidsing.

the class HtmlUtil method parse.

public HtmlNode parse(String in) {
    List<IntIntPair> pairs = new ArrayList<>();
    int pos0, pos1 = 0;
    while (0 <= (pos0 = in.indexOf("<", pos1)) && 0 <= (pos1 = in.indexOf(">", pos0 + 1))) pairs.add(IntIntPair.of(pos0, ++pos1));
    Fun<String, IntObjPair<String>> getNameFun = tag -> {
        int p0 = 1, p1 = p0 + 1, px = tag.length() - 1;
        char first = tag.charAt(p1);
        char last = tag.charAt(px - 1);
        int d;
        if (first == '!')
            return IntObjPair.of(0, tag);
        else {
            if (first == '/') {
                p1++;
                d = -1;
            } else if (last == '/') {
                px--;
                d = 0;
            } else
                d = 1;
            int ps0 = tag.indexOf(' ');
            int ps1 = 0 <= ps0 ? ps0 : px;
            return IntObjPair.of(d, tag.substring(p1, ps1));
        }
    };
    Deque<HtmlNode> deque = new ArrayDeque<>(List.of(new HtmlNode(null)));
    int prevp = 0;
    for (IntIntPair pair : pairs) {
        HtmlNode htmlNode = deque.element(), htmlNode1;
        int p0 = pair.t0;
        int px = pair.t1;
        htmlNode.children.add(new HtmlNode(in.substring(prevp, p0)));
        String tag = in.substring(p0, px);
        IntObjPair<String> dn = getNameFun.apply(tag);
        int d = dn.t0;
        String name = dn.t1;
        if (d == -1)
            while (!deque.isEmpty() && !String_.equals(getNameFun.apply(deque.pop().tag).t1, name)) ;
        else {
            htmlNode.children.add(htmlNode1 = new HtmlNode(tag));
            if (d == 1)
                deque.push(htmlNode1);
        }
        prevp = px;
    }
    return deque.pop();
}
Also used : List(java.util.List) IntObjPair(suite.primitive.adt.pair.IntObjPair) BiMap(suite.adt.map.BiMap) IntIntPair(suite.primitive.adt.pair.IntIntPair) HashBiMap(suite.adt.map.HashBiMap) ArrayDeque(java.util.ArrayDeque) Deque(java.util.Deque) Fun(suite.util.FunUtil.Fun) ArrayList(java.util.ArrayList) IntObjPair(suite.primitive.adt.pair.IntObjPair) ArrayList(java.util.ArrayList) ArrayDeque(java.util.ArrayDeque) IntIntPair(suite.primitive.adt.pair.IntIntPair)

Example 14 with Fun

use of suite.util.FunUtil.Fun in project suite by stupidsing.

the class Nodify method newNodifier.

@SuppressWarnings("unchecked")
private Nodifier newNodifier(Type type) {
    Nodifier nodifier;
    if (type instanceof Class) {
        Class<?> clazz = (Class<?>) type;
        if (clazz == boolean.class)
            nodifier = new Nodifier(object -> Atom.of(object.toString()), node -> node == Atom.TRUE);
        else if (clazz == int.class)
            nodifier = new Nodifier(object -> Int.of((Integer) object), node -> ((Int) node).number);
        else if (clazz == Chars.class)
            nodifier = new Nodifier(object -> new Str(object.toString()), node -> To.chars(((Str) node).value));
        else if (clazz == String.class)
            nodifier = new Nodifier(object -> new Str(object.toString()), node -> ((Str) node).value);
        else if (clazz.isEnum())
            nodifier = new Nodifier(object -> Atom.of(object.toString()), Read.from(clazz.getEnumConstants()).toMap(e -> Atom.of(e.toString()))::get);
        else if (clazz.isArray()) {
            Class<?> componentType = clazz.getComponentType();
            Nodifier nodifier1 = getNodifier(componentType);
            Fun<Object, Node> forward = object -> {
                Node node = Atom.NIL;
                for (int i = Array.getLength(object) - 1; 0 <= i; i--) node = Tree.of(TermOp.OR____, apply_(nodifier1, Array.get(object, i)), node);
                return node;
            };
            nodifier = new Nodifier(forward, node -> {
                List<Object> list = // 
                Read.from(// 
                Tree.iter(node, TermOp.OR____)).map(// 
                n -> apply_(nodifier1, n)).toList();
                int size = list.size();
                Object objects = Array.newInstance(componentType, size);
                for (int i = 0; i < size; i++) Array.set(objects, i, list.get(i));
                return objects;
            });
        } else if (// polymorphism
        clazz.isInterface())
            nodifier = new Nodifier(object -> {
                Class<?> clazz1 = object.getClass();
                Node n = apply_(getNodifier(clazz1), object);
                return Tree.of(TermOp.COLON_, Atom.of(clazz1.getName()), n);
            }, node -> {
                Tree tree = Tree.decompose(node, TermOp.COLON_);
                if (tree != null) {
                    Class<?> clazz1;
                    try {
                        clazz1 = Class.forName(((Atom) tree.getLeft()).name);
                    } catch (ClassNotFoundException ex) {
                        clazz1 = Fail.t(ex);
                    }
                    return apply_(getNodifier(clazz1), tree.getRight());
                } else
                    // happens when an enum implements an interface
                    return Fail.t("cannot instantiate enum from interfaces");
            });
        else {
            List<FieldInfo> fieldInfos = // 
            Read.from(// 
            inspect.fields(clazz)).map(field -> {
                Type type1 = field.getGenericType();
                return new FieldInfo(field, field.getName(), getNodifier(type1));
            }).toList();
            List<Pair<Atom, FieldInfo>> pairs = Read.from(fieldInfos).map(f -> Pair.of(Atom.of(f.name), f)).toList();
            nodifier = new Nodifier(object -> Rethrow.ex(() -> {
                Dict dict = new Dict();
                for (Pair<Atom, FieldInfo> pair : pairs) {
                    FieldInfo fieldInfo = pair.t1;
                    Node value = apply_(fieldInfo.nodifier, fieldInfo.field.get(object));
                    dict.map.put(pair.t0, Reference.of(value));
                }
                return dict;
            }), node -> Rethrow.ex(() -> {
                Map<Node, Reference> map = ((Dict) node).map;
                Object object1 = Object_.new_(clazz);
                for (Pair<Atom, FieldInfo> pair : pairs) {
                    FieldInfo fieldInfo = pair.t1;
                    Node value = map.get(pair.t0).finalNode();
                    fieldInfo.field.set(object1, apply_(fieldInfo.nodifier, value));
                }
                return object1;
            }));
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType pt = (ParameterizedType) type;
        Type rawType = pt.getRawType();
        Type[] typeArgs = pt.getActualTypeArguments();
        Class<?> clazz = rawType instanceof Class ? (Class<?>) rawType : null;
        if (collectionClasses.contains(clazz)) {
            Nodifier nodifier1 = getNodifier(typeArgs[0]);
            nodifier = new Nodifier(object -> {
                Tree start = Tree.of(null, null, null), tree = start;
                for (Object o : (Collection<?>) object) {
                    Tree tree0 = tree;
                    Tree.forceSetRight(tree0, tree = Tree.of(TermOp.OR____, apply_(nodifier1, o), null));
                }
                Tree.forceSetRight(tree, Atom.NIL);
                return start.getRight();
            }, node -> {
                List<Object> list = Read.from(Tree.iter(node, TermOp.OR____)).map(n -> apply_(nodifier1, n)).toList();
                Collection<Object> object1 = (Collection<Object>) instantiate(clazz);
                object1.addAll(list);
                return object1;
            });
        } else if (mapClasses.contains(clazz)) {
            Nodifier kn = getNodifier(typeArgs[0]);
            Nodifier vn = getNodifier(typeArgs[1]);
            nodifier = new Nodifier(object -> {
                Dict dict = new Dict();
                for (Entry<?, ?> e : ((Map<?, ?>) object).entrySet()) dict.map.put(apply_(kn, e.getKey()), Reference.of(apply_(vn, e.getValue())));
                return dict;
            }, node -> {
                Map<Node, Reference> map = ((Dict) node).map;
                Map<Object, Object> object1 = (Map<Object, Object>) instantiate(clazz);
                for (Entry<Node, Reference> e : map.entrySet()) object1.put(apply_(kn, e.getKey()), apply_(vn, e.getValue().finalNode()));
                return object1;
            });
        } else
            nodifier = getNodifier(rawType);
    } else
        nodifier = Fail.t("unrecognized type " + type);
    return nodifier;
}
Also used : Read(suite.streamlet.Read) Array(java.lang.reflect.Array) HashMap(java.util.HashMap) Fun(suite.util.FunUtil.Fun) ArrayList(java.util.ArrayList) Node(suite.node.Node) HashSet(java.util.HashSet) Map(java.util.Map) Dict(suite.node.Dict) Reference(suite.node.Reference) Inspect(suite.inspect.Inspect) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) TermOp(suite.node.io.TermOp) Field(java.lang.reflect.Field) Chars(suite.primitive.Chars) Tree(suite.node.Tree) Pair(suite.adt.pair.Pair) List(java.util.List) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Atom(suite.node.Atom) Entry(java.util.Map.Entry) Int(suite.node.Int) Str(suite.node.Str) Node(suite.node.Node) Int(suite.node.Int) Str(suite.node.Str) ParameterizedType(java.lang.reflect.ParameterizedType) Entry(java.util.Map.Entry) Tree(suite.node.Tree) Fun(suite.util.FunUtil.Fun) Pair(suite.adt.pair.Pair) Reference(suite.node.Reference) Atom(suite.node.Atom) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Dict(suite.node.Dict) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 15 with Fun

use of suite.util.FunUtil.Fun in project suite by stupidsing.

the class FunCreatorTest method testObject.

@Test
public void testObject() {
    Int_Int inc = i -> i + 1;
    Iterate<FunExpr> fun = i -> f.object(inc).invoke("apply", i);
    assertEquals(3, LambdaInstance.of(Int_Int.class, fun).newFun().apply(2));
}
Also used : Reference(suite.node.Reference) Suite(suite.Suite) Flt_Flt(suite.primitive.Flt_Flt) Dump(suite.inspect.Dump) PrintlnFunExpr(suite.jdk.gen.FunExprM.PrintlnFunExpr) Source(suite.util.FunUtil.Source) Assert.assertTrue(org.junit.Assert.assertTrue) TermOp(suite.node.io.TermOp) Test(org.junit.Test) Fun(suite.util.FunUtil.Fun) ProfileFunExpr(suite.jdk.gen.FunExprM.ProfileFunExpr) Tree(suite.node.Tree) Node(suite.node.Node) IntSource(suite.primitive.IntPrimitives.IntSource) Iterate(suite.util.FunUtil.Iterate) BiPredicate(java.util.function.BiPredicate) LambdaInstance(suite.jdk.lambda.LambdaInstance) Map(java.util.Map) Type(org.apache.bcel.generic.Type) FunExpr(suite.jdk.gen.FunExpression.FunExpr) Int(suite.node.Int) LambdaInterface(suite.jdk.lambda.LambdaInterface) Int_Int(suite.primitive.Int_Int) Assert.assertEquals(org.junit.Assert.assertEquals) Int_Int(suite.primitive.Int_Int) PrintlnFunExpr(suite.jdk.gen.FunExprM.PrintlnFunExpr) ProfileFunExpr(suite.jdk.gen.FunExprM.ProfileFunExpr) FunExpr(suite.jdk.gen.FunExpression.FunExpr) Test(org.junit.Test)

Aggregations

Fun (suite.util.FunUtil.Fun)31 Node (suite.node.Node)18 Fail (suite.util.Fail)13 List (java.util.List)12 TermOp (suite.node.io.TermOp)12 ArrayList (java.util.ArrayList)11 Map (java.util.Map)11 Suite (suite.Suite)11 Tree (suite.node.Tree)11 Source (suite.util.FunUtil.Source)11 Atom (suite.node.Atom)10 Reference (suite.node.Reference)10 Pair (suite.adt.pair.Pair)9 Int (suite.node.Int)9 Read (suite.streamlet.Read)9 Iterate (suite.util.FunUtil.Iterate)8 To (suite.util.To)7 Collections (java.util.Collections)6 Entry (java.util.Map.Entry)6 LogUtil (suite.os.LogUtil)6