Search in sources :

Example 1 with Loop

use of jcog.exe.Loop in project narchy by automenta.

the class WorkerMultiExecTest method test1.

@Test
public void test1() {
    int threads = 3;
    Focus.DefaultRevaluator reval = new Focus.DefaultRevaluator();
    WorkerMultiExec exe = new WorkerMultiExec(reval, threads, 16, 3);
    NAR n = new NARS().exe(exe).get();
    AtomicLong dutyTimeNS = new AtomicLong();
    DummyCan a = new DummyCan("a", dutyTimeNS, n, (int j) -> Util.sleep(1 * j)).value(4f);
    DummyCan b = new DummyCan("b", dutyTimeNS, n, (int j) -> Util.sleep(1 * j)).value(1f);
    DummyCan c = new DummyCan("c", dutyTimeNS, n, (int j) -> Util.sleep(2 * j)).value(1f);
    // n.onCycle(nn -> {
    // Focus.Schedule s = exe.focus.schedule.read();
    // System.out.println(nn.time() + " " +
    // Arrays.toString(s.active) + "->" + n4(s.weight));
    // });
    long start = System.nanoTime();
    Loop l = n.startFPS(5f);
    Util.sleep(4000);
    l.stop();
    long totalTimeNS = (System.nanoTime() - start) * threads;
    System.out.println("dutyTime=" + timeStr(dutyTimeNS.get()) + " , totalTime=" + timeStr(totalTimeNS) + ", efficiency=" + ((double) dutyTimeNS.get()) / totalTimeNS);
    System.out.println(a.executed.get());
    System.out.println(b.executed.get());
    System.out.println(c.executed.get());
    System.out.println(exe.focus);
    assertEquals(3 + 1, exe.focus.choice.size());
    assertEquals(expectedDuty(a) / expectedDuty(b), ((float) a.executed.get()) / b.executed.get(), 0.5f);
    assertEquals(expectedDuty(a) / expectedDuty(c) / 2, ((float) a.executed.get()) / c.executed.get(), 0.5f);
}
Also used : NARS(nars.NARS) Loop(jcog.exe.Loop) AtomicLong(java.util.concurrent.atomic.AtomicLong) NAR(nars.NAR) Test(org.junit.jupiter.api.Test)

Example 2 with Loop

use of jcog.exe.Loop in project narchy by automenta.

the class ExampleBackgroundRemovalStationary method main.

public static void main(String[] args) {
    WebCam c = new WebCam();
    Tex output = new Tex();
    SpaceGraph.window(new Gridding(c.view(), output.view()), 800, 800);
    // String fileName = UtilIO.pathExample("background/horse_jitter.mp4"); // degraded performance because of jitter
    // String fileName = UtilIO.pathExample("tracking/chipmunk.mjpeg"); // Camera moves.  Stationary will fail here
    // Comment/Uncomment to switch input image type
    ImageType imageType = ImageType.single(GrayF32.class);
    // ImageType imageType = ImageType.il(3, InterleavedF32.class);
    // ImageType imageType = ImageType.il(3, InterleavedU8.class);
    // Configuration for Gaussian model.  Note that the threshold changes depending on the number of image bands
    // 12 = gray scale and 40 = color
    ConfigBackgroundGaussian configGaussian = new ConfigBackgroundGaussian(40, 0.0005f);
    configGaussian.initialVariance = 100;
    configGaussian.minimumDifference = 10f;
    // Comment/Uncomment to switch algorithms
    BackgroundModelStationary background = // FactoryBackgroundModel.stationaryBasic(new ConfigBackgroundBasic(35, 0.005f), imageType);
    FactoryBackgroundModel.stationaryGaussian(configGaussian, imageType);
    // Declare storage for segmented image.  1 = moving foreground and 0 = background
    GrayU8 segmented = new GrayU8(c.width, c.height);
    GrayF32 input = new GrayF32(c.width, c.height);
    BufferedImage segmentedVis = new BufferedImage(c.width, c.height, BufferedImage.TYPE_INT_RGB);
    new Loop(10f) {

        @Override
        public boolean next() {
            BufferedImage img = c.image;
            if (img != null) {
                ConvertBufferedImage.convertFrom(img, input, true);
                // long before = System.nanoTime();
                background.segment(input, segmented);
                background.updateBackground(input);
                byte[] b = segmented.data;
                for (int i = 0; i < b.length; i++) {
                    if (b[i] != 0)
                        b[i] = 127;
                }
                output.update(// segmented
                ConvertBufferedImage.convertTo(segmented, segmentedVis));
            }
            // }
            return true;
        }
    };
}
Also used : Loop(jcog.exe.Loop) Gridding(spacegraph.space2d.container.Gridding) BackgroundModelStationary(boofcv.alg.background.BackgroundModelStationary) GrayF32(boofcv.struct.image.GrayF32) Tex(spacegraph.video.Tex) WebCam(spacegraph.video.WebCam) GrayU8(boofcv.struct.image.GrayU8) BufferedImage(java.awt.image.BufferedImage) ConvertBufferedImage(boofcv.io.image.ConvertBufferedImage) ImageType(boofcv.struct.image.ImageType) ConfigBackgroundGaussian(boofcv.factory.background.ConfigBackgroundGaussian)

Example 3 with Loop

use of jcog.exe.Loop in project narchy by automenta.

the class GUI method main.

public static void main(String[] args) throws IOException, Narsese.NarseseException {
    NAR nar = NARchy.ui();
    // 10hz alpha
    Loop loop = nar.startFPS(10f);
    // ((NARLoop) loop).throttle.set(0.1f);
    // 1. try to open a Spacegraph openGL window
    logger.info("start SpaceGraph UI");
    // window(new ConsoleTerminal(new TextUI(nar).session(8f)) {
    // {
    // Util.pause(50); term.addInput(KeyStroke.fromString("<pageup>")); //HACK trigger redraw
    // }
    // }, 800, 600);
    PhyWall w = SpaceGraph.wall(800, 600);
    ((ZoomOrtho) w.root()).scaleMin = 100f;
    ((ZoomOrtho) w.root()).scaleMax = 1500;
    w.put(new Gridding(new OmniBox()), 6, 1);
    w.put(Vis.top(nar), 4, 4);
// nar.inputNarsese(new FileInputStream("/home/me/d/sumo_merge.nal"));
}
Also used : Loop(jcog.exe.Loop) Gridding(spacegraph.space2d.container.Gridding) PhyWall(spacegraph.space2d.widget.windo.PhyWall) OmniBox(spacegraph.space2d.widget.meta.OmniBox)

Example 4 with Loop

use of jcog.exe.Loop in project narchy by automenta.

the class NAgentX method runRT.

public static NAR runRT(Function<NAR, NAgent> init, float narFPS, float agentFPS) {
    // The.Subterms.the =
    // The.Subterms.CaffeineSubtermBuilder.get();
    // The.Subterms.HijackSubtermBuilder.get();
    // The.Subterms.SoftSubtermBuilder.get();
    // The.Compound.the =
    // The.Compound.
    // //SoftCompoundBuilder.get();
    // CaffeineCompoundBuilder.get();
    float clockFPS = // agentFPS;
    narFPS;
    RealTime clock = clockFPS >= 10 / 2f ? /* nyquist threshold between decisecond (0.1) and centisecond (0.01) clock resolution */
    new RealTime.CS(true) : new RealTime.DSHalf(true);
    clock.durFPS(clockFPS);
    // Function<NAR, PrediTerm<Derivation>> deriver = Deriver.deriver(8
    // , "motivation.nal"
    // //., "relation_introduction.nal"
    // );
    // int THREADS = Math.max(1, Runtime.getRuntime().availableProcessors() - 1);
    // Predicate<Activate> randomBool = (a) -> ThreadLocalRandom.current().nextBoolean();
    // exe.add(new FocusExec(), (x) -> true);
    // exe.add(new FocusExec() {
    // {
    // concepts.setCapacity(32);
    // }
    // },
    // (x) -> true);
    NAR n = new NARS().exe(new WorkerMultiExec(// new Focus.DefaultRevaluator(),
    new Focus.AERevaluator(new XoRoShiRo128PlusRandom(1)), 256, 8192) {

        {
            Util.setExecutor(this);
        }
    }).time(clock).deriverAdd(1, 1).deriverAdd(2, 2).deriverAdd(3, 3).deriverAdd(5, 5).deriverAdd(6, 8).deriverAdd("motivation.nal").index(new CaffeineIndex(// 800 * 1024,
    2500 * 1024, // Integer.MAX_VALUE,
    c -> {
        return (int) Math.ceil(c.voluplexity());
    // return Math.round(
    // ((float)c.voluplexity())
    // / (1 + 100 * (c.termlinks().priSum() + c.tasklinks().priSum()))
    // //(c.beliefs().size() + c.goals().size()))
    // );
    })).get();
    // n.defaultWants();
    n.dtMergeOrChoose.set(true);
    // 0.5f //nyquist
    n.dtDither.set(1f);
    // n.timeFocus.set(4);
    n.confMin.set(0.01f);
    n.freqResolution.set(0.01f);
    n.termVolumeMax.set(40);
    n.beliefConfDefault.set(0.9f);
    n.goalConfDefault.set(0.9f);
    float priFactor = 0.2f;
    n.beliefPriDefault.set(1f * priFactor);
    n.goalPriDefault.set(1f * priFactor);
    n.questionPriDefault.set(1f * priFactor);
    n.questPriDefault.set(1f * priFactor);
    n.activationRate.set(0.5f);
    NAgent a = init.apply(n);
    // new RLBooster(a, HaiQAgent::new, 1);
    // //            @Override
    // //            protected long matchTime(Task task) {
    // //
    // //                //future lookahead to catalyze prediction
    // //                return n.time() +
    // //                        Util.sqr(n.random().nextInt(3)) * n.dur();
    // //
    // //            }
    // };
    // {
    // AgentBuilder b = MetaGoal.newController(a);
    // //                .in(a::dexterity)
    // //                .in(new FloatNormalized(()->a.reward).decay(0.9f))
    // //                .in(new FloatNormalized(
    // //                        ((Emotivation) n.emotion).cycleDTRealMean::getValue)
    // //                            .decay(0.9f)
    // //                )
    // b.in(new FloatNormalized(
    // //TODO use a Long-specific impl of this:
    // new FloatFirstOrderDifference(n::time, () -> n.emotion.deriveTask.getValue().longValue())
    // ).relax(0.99f))
    // //                .in(new FloatNormalized(
    // //                        //TODO use a Long-specific impl of this:
    // //                        new FirstOrderDifferenceFloat(n::time, () -> n.emotion.conceptFirePremises.getValue().longValue())
    // //                    ).decay(0.9f)
    // .in(new FloatNormalized(
    // () -> n.emotion.busyVol.getSum()
    // ).relax(0.99f))
    // .out(2, (onOff)->{
    // switch(onOff) {
    // case 0:
    // a.enabled.set(false); //pause
    // break;
    // case 1:
    // a.enabled.set(true); //un-pause
    // break;
    // }
    // })
    // //                ).out(
    // //                        new StepController((x) -> n.time.dur(Math.round(x)), 1, n.dur(), n.dur()*2)
    // //                .out(
    // //                        StepController.harmonic(n.confMin::set, 0.01f, 0.5f)
    // //                )//.out(
    // //                        StepController.harmonic(n.truthResolution::setValue, 0.01f, 0.08f)
    // //                ).out(
    // //                        StepController.harmonic(a.curiosity::setValue, 0.01f, 0.16f)
    // //                ).get(n);
    // 
    // ;
    // new AgentService(new MutableFloat(1), n, b.get());
    // }
    // n.dtMergeOrChoose.setValue(true);
    // STMLinkage stmLink = new STMLinkage(n, 1, false);
    // LinkClustering linkClusterPri = new LinkClustering(n, Prioritized::priElseZero /* anything temporal */,
    // 32, 128);
    // LinkClustering linkClusterConf = new LinkClustering(n, (t) -> t.isBeliefOrGoal() ? t.conf() : Float.NaN,
    // 4, 16);
    // SpaceGraph.window(col(
    // new STMView.BagClusterVis(n, linkClusterPri.bag),
    // new STMView.BagClusterVis(n, linkClusterConf.bag)
    // ), 800, 600);
    // ConjClustering conjClusterBinput = new ConjClustering(n, BELIEF, (Task::isInput), 8, 32);
    ConjClustering conjClusterBany = new ConjClustering(n, BELIEF, (t -> true), 8, 64);
    // ConjClustering conjClusterG = new ConjClustering(n, GOAL, (t -> true), 4, 16);
    // ArithmeticIntroduction arith = new ArithmeticIntroduction(4, n);
    // RelationClustering relCluster = new RelationClustering(n,
    // (t)->t.isBelief() && !t.isEternal() && !t.term().isTemporal() ? t.conf() : Float.NaN,
    // 8, 32);
    // ConjClustering conjClusterG = new ConjClustering(n, GOAL, (t->true),8, 32);
    // n.runLater(() -> {
    // //            AudioContext ac = new AudioContext();
    // //            ac.start();
    // //            Clock aclock = new Clock(ac, 1000f / (agentFPS * 0.5f));
    // //            new Metronome(aclock, n);
    // new VocalCommentary(null, a);
    // //ac.out.dependsOn(aclock);
    // });
    // /needs tryContent before its safe
    Inperience inp = new Inperience(n, 12);
    // 
    // Abbreviation abb = new Abbreviation(n, "z", 3, 6, 10f, 32);
    // reflect.ReflectSimilarToTaskTerm refSim = new reflect.ReflectSimilarToTaskTerm(16, n);
    // reflect.ReflectClonedTask refTask = new reflect.ReflectClonedTask(16, n);
    // a.trace = true;
    // n.onTask(t -> {
    // if (t instanceof DerivedTask)
    // System.out.println(t);
    // });
    // NInner nin = new NInner(n);
    // nin.start();
    // AgentService mc = MetaGoal.newController(a);
    // init();
    // n.onCycle(nn -> {
    // float lag = narLoop.lagSumThenClear() + a.running().lagSumThenClear();
    // //n.emotion.happy(-lag);
    // //n.emotion.happy(n.emotion.busyPri.getSum()/50000f);
    // });
    // new Anoncepts(8, n);
    // new Implier(2f, a,
    // 1
    // //0,1,4
    // );
    // 
    // window(new MatrixView(p.in, (x, gl) -> {
    // Draw.colorBipolar(gl, x);
    // return 0;
    // }), 100, 100);
    // get ready
    System.gc();
    n.runLater(() -> {
        chart(a);
        SpaceGraph.window(Vis.top(a.nar()), 800, 800);
        // window(new ConceptView(a.happy,n), 800, 600);
        n.on(a);
        // START AGENT
        Loop aLoop = a.runFPS(agentFPS);
    // n.runLater(() -> {
    // new Deriver(a.fire(), Derivers.deriver(6, 8,
    // "motivation.nal"
    // //, "goal_analogy.nal"
    // ).apply(n).deriver, n); //{
    // });
    });
    Loop loop = n.startFPS(narFPS);
    return n;
}
Also used : Bitmap2DSensor(nars.util.signal.Bitmap2DSensor) IntConsumer(java.util.function.IntConsumer) AspectAlign(spacegraph.space2d.container.AspectAlign) Auvent(net.beadsproject.beads.core.Auvent) AutoSurface(spacegraph.space2d.widget.meta.AutoSurface) RealTime(nars.time.RealTime) nars.$.$$(nars.$.$$) DoubleHistogram(org.HdrHistogram.DoubleHistogram) SpaceGraphPhys3D(spacegraph.space3d.SpaceGraphPhys3D) Vis(nars.gui.Vis) Bitmap2D(jcog.signal.Bitmap2D) XoRoShiRo128PlusRandom(jcog.math.random.XoRoShiRo128PlusRandom) Term(nars.term.Term) nars.video(nars.video) ConsoleTerminal(spacegraph.space2d.widget.console.ConsoleTerminal) Loop(jcog.exe.Loop) UGen(net.beadsproject.beads.core.UGen) BufferedImage(java.awt.image.BufferedImage) Util(jcog.Util) FloatArrayList(org.eclipse.collections.impl.list.mutable.primitive.FloatArrayList) Nullable(org.jetbrains.annotations.Nullable) WaveFactory(net.beadsproject.beads.data.WaveFactory) WorkerMultiExec(nars.exe.WorkerMultiExec) SpaceGraph(spacegraph.SpaceGraph) EmotionPlot(nars.gui.EmotionPlot) Tense(nars.time.Tense) net.beadsproject.beads.ugens(net.beadsproject.beads.ugens) Focus(nars.exe.Focus) Surface(spacegraph.space2d.Surface) Function(java.util.function.Function) Supplier(java.util.function.Supplier) nars.$.$(nars.$.$) WindowToggleButton(spacegraph.space2d.widget.meta.WindowToggleButton) SubOrtho(spacegraph.space2d.hud.SubOrtho) Gridding.grid(spacegraph.space2d.container.Gridding.grid) EdgeDirected(spacegraph.space2d.container.EdgeDirected) FloatProcedure(org.eclipse.collections.api.block.procedure.primitive.FloatProcedure) Inperience(nars.op.mental.Inperience) Files(java.nio.file.Files) PushButton(spacegraph.space2d.widget.button.PushButton) DynamicConceptSpace(nars.gui.graph.DynamicConceptSpace) IOException(java.io.IOException) AudioContext(net.beadsproject.beads.core.AudioContext) IntObjectPair(org.eclipse.collections.api.tuple.primitive.IntObjectPair) java.awt(java.awt) TextEdit(spacegraph.space2d.widget.console.TextEdit) BELIEF(nars.Op.BELIEF) ConjClustering(nars.op.stm.ConjClustering) CaffeineIndex(nars.index.term.map.CaffeineIndex) Loop(jcog.exe.Loop) Inperience(nars.op.mental.Inperience) CaffeineIndex(nars.index.term.map.CaffeineIndex) WorkerMultiExec(nars.exe.WorkerMultiExec) XoRoShiRo128PlusRandom(jcog.math.random.XoRoShiRo128PlusRandom) Focus(nars.exe.Focus) ConjClustering(nars.op.stm.ConjClustering) RealTime(nars.time.RealTime)

Aggregations

Loop (jcog.exe.Loop)4 BufferedImage (java.awt.image.BufferedImage)2 BackgroundModelStationary (boofcv.alg.background.BackgroundModelStationary)1 ConfigBackgroundGaussian (boofcv.factory.background.ConfigBackgroundGaussian)1 ConvertBufferedImage (boofcv.io.image.ConvertBufferedImage)1 GrayF32 (boofcv.struct.image.GrayF32)1 GrayU8 (boofcv.struct.image.GrayU8)1 ImageType (boofcv.struct.image.ImageType)1 java.awt (java.awt)1 IOException (java.io.IOException)1 Files (java.nio.file.Files)1 AtomicLong (java.util.concurrent.atomic.AtomicLong)1 Function (java.util.function.Function)1 IntConsumer (java.util.function.IntConsumer)1 Supplier (java.util.function.Supplier)1 Util (jcog.Util)1 XoRoShiRo128PlusRandom (jcog.math.random.XoRoShiRo128PlusRandom)1 Bitmap2D (jcog.signal.Bitmap2D)1 nars.$.$ (nars.$.$)1 nars.$.$$ (nars.$.$$)1