SophiaPretty

(5)

$14/per page/Negotiable

About SophiaPretty

Levels Tought:
Elementary,Middle School,High School,College,University,PHD

Expertise:
Accounting,Algebra See all
Accounting,Algebra,Applied Sciences,Architecture and Design,Art & Design,Biology,Business & Finance,Calculus,Chemistry,Communications,Computer Science,Economics,Engineering,English,Environmental science,Essay writing Hide all
Teaching Since: Jul 2017
Last Sign in: 206 Weeks Ago, 3 Days Ago
Questions Answered: 15833
Tutorials Posted: 15827

Education

  • MBA,PHD, Juris Doctor
    Strayer,Devery,Harvard University
    Mar-1995 - Mar-2002

Experience

  • Manager Planning
    WalMart
    Mar-2001 - Feb-2009

Category > Computer Science Posted 05 Jan 2018 My Price 10.00

(TernaryLogic.java) I Should be receiving ONE java

I have attached my current file that needs to be updated.  (TernaryLogic.java)  I Should be receiving ONE java file in return with the simulation homework implemented.  I have also attached previous years solutions that are very very similar.  Please take a look at these files to base off of. ( LogicCircuit.java , NeuronNetwork.java )

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Write a Java program, in file TernaryLogic.java that can read the description of a system of logic gates from a file called f (presuming that this file exists) when you type the following command to run your program:

[HawkID@serv15 project]$ java TernaryLogic f
  

 

When your program is run, it should either:

  • Output error messages if the logic circuit description contains errors, or
  • Output a trace of the events that occur in a simulation of that logic circuit, until there are no more events.
  • It should not output a copy of the logic circuit (although you might want to keep the output code handy for debugging, do not include it in your final submission.

here is an example description (in the format used for MP3).

gate TIMER istrue     9.0
wire TIMER TIMER      1.0

gate ENABLE isunknown 1.0
wire TIMER ENABLE     1.0

gate CLOCK isfalse    0.5
gate CONTROL min 2    0.5
wire CLOCK CONTROL    0.5
wire CONTROL CLOCK    0.5
wire ENABLE CONTROL   0.5

gate FLIP neg         0.5
gate MIX max 2        0.5
wire TIMER FLIP       1.0
wire FLIP MIX         1.0
wire MIX MIX          1.0

The simulation should implement the following model:

The initial state of the simulator is that all inputs and all outputs of gates and wires are unknown, represented by the value 1. In the case of istrue and isfalse gates, this is an unstable state. Before the simulation begins, each such gate should immediately schedule an output transition from unknown to false (represented by the value 0) at a time equal to the gate's delay. Similarly, for isunknown gates, an output transition to true (represented by the value 2) should be scheduled.

  • Wires transmit their input values to their outputs after the indicated delay.
  • Gate outputs respond to the states of their inputs after the indicated delay.
  • Gates input the ternarymin,max,neg,istrue,isfalseandisunknownoperators on the values 0 (false), 1 (unknown), and 2 (true).

(This model leaves out a huge number of features of real digital logic, most notably, the fact that logic gates act as low pass filters. That is, if an output change is followed swiftly enough by another output change, the first value is lost.)

The output should show one line of text for each change of the output of a logic gate. The output should show the time, the gate name and the new value (0, 1 or 2), with no additional text aside from blanks separating fields.

Grading criteria will be as usual: No credit will be given to programs that do not represent a substantial attempt at meeting the requirements of this assignment. Your program must:

  • Begin with a header comment giving the source file name.
  • Contain Javadoc comments claiming authorship and declaring the version to beMP4.
  • Be cleanly and readably indented.
  • Use appropriate variable names.
  • Not contain excessive white-space. (Double-spaced text wastes paper.)
  • Respond appropriately to errors in the input.
  • Generate appropriate output if there were no errors in the input.
  • Not demonstrate any unhandled or mishandled exceptions.

 

Note that the requirements for header comments in the file header are absolute. Your name must appear in the form that it appears on your ID card. The TAs will not waste their time doing detective work to attempt to figure out who submitted what code.

Submission: Your solution should consist of a single file, with one public method, main. (Later, we will chop the file into smaller more managable pieces, as it grows.)

  • // LogicCircuit.java
    /**
     * A logic circuit simulator
     * @version MP3
     */

    import java.util.Arrays;
    import java.util.List;
    import java.util.LinkedList;
    import java.util.PriorityQueue;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    class Simulator {
            /** Framework for discrete event simulation.
             */

            public interface Action {
                    // actions contain the specific code of each event
                    void trigger( float time );
            }

            private static class Event {
                    public float time; // the time of this event
                    public Action act; // what to do at that time
            }

            private static PriorityQueue <Event> eventSet
            = new PriorityQueue <Event> (
                    (Event e1, Event e2) -> Float.compare( e1.time, e2.time )
            );

            static void schedule( float time, Action act ) {
                    /** Call schedule to make act happen at time.
                     *  Users typically pass the action as a lambda expression:
                     *  <PRE>
                     *  Simulator.schedule(t,(float time)->method(params,time))
                     *  </PRE>
                     */
                    Event e = new Event();
                    e.time = time;
                    e.act = act;
                    eventSet.add( e );
            }

            static void run() {
                    /** Call run after scheduling some initial events
                     *  to run the simulation.
                     */
                    while (!eventSet.isEmpty()) {
                            Event e = eventSet.remove();
                            e.act.trigger( e.time );
                    }
            }
    }

    class Errors {
        /** Error reporting framework
         */
        static void fatal( String message ) {
            /** Report a fatal error with the given message
             */
            System.err.println( message );
            System.exit( 1 );
        }

        static void warn( String message ) {
            /** Report a nonfatal error with the given message
             */
            System.err.println( message );
        }
    }

    class SyntaxCheck {
        /** Syntax checking support
         */

        public interface ByName {
            // crutch to allow lambda evaluation of error message string
            String s();
        }

        static void lineEnd( Scanner sc, ByName c ) {
            /** Check for end of line on sc,
             *  Use c to provide context in any error message
             */
            String s = sc.nextLine();
            if (!s.isEmpty()) {
                Errors.warn(
                    c.s()
                    + " has non-empty line end '"
                    + s
                    + "'"
                );
            }
        }
    }

    class Wire {
        /** Wires link gates.
         *  @see Gate
         */
        private float delay;    // delay of this wire
        private Gate  driven;    // what gate does this wire drive
        private int   input;    // what input of driven does this wire drive

        private Gate  driver;    // what gate drives this wire

        // initializer -- note:  No outside code uses the default initializer!
        public static Wire scan( Scanner sc ) {
            /** Initialize a wire by scanning its description from sc.
             *  Returns null if the description contains errors.
             */
            Wire w = new Wire();
            Wire returnValue = w;

            String srcName = sc.next();
            w.driver = LogicCircuit.findGate( srcName );
            String dstName = sc.next();
            w.driven = LogicCircuit.findGate( dstName );
            String inputName = sc.next();

            if (w.driver == null) {
                Errors.warn(
                    "Wire '" + srcName + "' '" + dstName
                    + "' -- the first name is undefined"
                );
                returnValue = null;
            } else {
                // inform gate that drives this wire that it does so
                w.driver.setDriven( w );
            }

            if (w.driven == null) {
                Errors.warn(
                    "Wire '" + srcName + "' '" + dstName
                    + "' -- the second name is undefined"
                );
                returnValue = null;
            } else {
                w.input = w.driven.inputNumber( inputName );
                if (w.input < 0 ){
                    Errors.warn(
                        "Wire '" + srcName + "' '" + dstName
                        + "' '" + inputName
                        + "' -- the input name is not allowed"
                    );
                    returnValue = null;
                }
            }

            if (!sc.hasNextFloat()) {
                Errors.warn(
                    "Wire '" + srcName + "' '" + dstName + "'"
                    + "-- delay not specified"
                );
                returnValue = null;
            } else {
                w.delay = sc.nextFloat();
            }

            SyntaxCheck.lineEnd(
                sc, () -> "wire '" + srcName + "' '" + dstName + "'"
            );
            return returnValue;
        }

        public String toString() {
            /** Convert a wire back to its textual description
             */
            return  "wire "
                + driver.name + ' '
                + driven.name + ' '
                + driven.inputName( input ) + ' '
                + delay
            ;
        }

        public void inputChange( float t, boolean v ) {
            /** Simulation event service routine called
             *  when the input to a wire changes at time t to value v.
             */
            Simulator.schedule(
                t + delay,
                (float time) -> this.outputChange( time, v )
            );
        }

        public void outputChange( float t, boolean v ) {
            /** Simulation event service routine called
             *  when the output of a wire changes at time t to value v.
             */
            driven.inputChange( t, input, v );
        }
    }

    abstract class Gate {
        /** Gates are driven by and drive wires.
         *  @see Wire
         */
        String name;    // name of this gate; null signals invalid gate

        private LinkedList <Wire> driven = new LinkedList <Wire> ();
        // driven is (eventually) a list of all wires driven by this gate

        private List <String> inputList;  // the list of allowed input names
        private boolean[] inputUsed;      // for each input, is it in use?
        boolean[] inputValue;     // for each input, current value.
        boolean   outputValue;    // most recent computed output value.

        float delay;    // delay of this gate
       
        // initializer -- note:  called only by implementing classes
        public void scan( Scanner sc, List <String> inputs ) {
            /** Initialize a gate scanning its description from sc.
             *  Returns name = null if the description contains errors.
             */

            name = sc.next();
            String returnName = name;

            inputList = inputs;
            inputUsed = new boolean[ inputList.size() ];
            inputValue = new boolean[ inputList.size() ];
            for (int i = 0; i < inputUsed.length; i++) {
                inputUsed[i] = false;
                inputValue[i] = false;
            }
            outputValue = false;

            if (LogicCircuit.findGate( name ) != null) {
                Errors.warn( "Gate '" + name + "' redefined" );
                returnName = null;
            }

            if (!sc.hasNextFloat()) {
                Errors.warn(
                    "Gate '" + name
                    + "' -- delay not specified"
                );
                returnName = null;
            } else {
                delay = sc.nextFloat();
            }

            SyntaxCheck.lineEnd(
                sc, () -> "Gate '" + name + "'"
            );

            name = returnName;
        }

        public void setDriven( Wire w ) {
            /** Inform this gate that it drives wire w
             */
            driven.add( w );
        }

        public int inputNumber( String in ) {
            /** Given an input name, returns the corresponding number.
             *  Also checks that the name has not been used before;
             *  if it has been used or is an illegal name, returns -1.
             */
            int i = inputList.indexOf( in );
            if ( i >= 0 ) {
                if (inputUsed[i]) {
                    i = -1; // input already in use
                } else {
                    inputUsed[i] = true;
                }
            }
            return i;
        }

        public String inputName( int in ) {
            /** Given an input number, returns the corresponding name.
             *  and also check off the fact that it has been used.
             */
            return inputList.get( in );
        }

        public void checkInputs() {
            /** Check to see that all inputs of this gate are connected.
             */
            for (int i = 0; i < inputUsed.length; i++) {
                if (inputUsed[i] == false) {
                    Errors.warn(
                        "Gate " + name + ' '
                        + inputList.get( i )
                        + " -- input not connected"
                    );
                }
            }
        }

        public abstract String toString();
            /** Convert a gate back to its textual description
             */

        public abstract void inputChange( float t, int i, boolean v );
            /** Simulation event service routine called
             *  when input i of this gate changes at time t to value v.
             *  What to do at an input change depends on the gate type;
             *  it may do nothing, it may schedule an output change.
             */

        public void outputChange( float t, boolean v ) {
            /** Simulation event service routine called
             *  when the output of this gate changes at time t to value v.
             *  At this point, output changes are gate type independent.
             */

            System.out.println(
                "Time " + t + " Gate " + name + " changes to " + v + '.'
            );

            for (Wire w: driven) w.inputChange( t, v );
        }
    }

    class AndGate extends Gate {
        private AndGate() {} // prevent outsiders from using the initializer
        private static List <String> inputs = Arrays.asList( "in1", "in2" );

        public static Gate scan( Scanner sc ) {
            AndGate g = new AndGate();
            g.scan( sc, inputs );
            if (g.name == null) g = null;
            return g;
        }

        public String toString() {
            /** Convert an intersection back to its textual description
             */
            return "gate and " + name + ' ' + delay;
        }

        public void inputChange( float t, int i, boolean v ) {
            /** Simulation event service routine called
             *  when input i of this and gate changes at time t to value v.
             */

            boolean newValue = true;
            inputValue[i] = v;
            for (boolean vi: inputValue) if (!vi) newValue = false;
           
            if (newValue != outputValue) {
                outputValue = newValue;
                Simulator.schedule(
                    t + delay,
                    (float time)
                           -> this.outputChange( time, outputValue )
                );
            }
        }
    }

    class OrGate extends Gate {
        private OrGate() {} // prevent outsiders from using the initializer
        private static List <String> inputs = Arrays.asList( "in1", "in2" );

        public static Gate scan( Scanner sc ) {
            OrGate g = new OrGate();
            g.scan( sc, inputs );
            if (g.name == null) g = null;
            return g;
        }

        public String toString() {
            /** Convert an or gate back to its textual description
             */
            return "gate or " + name + ' ' + delay;
        }

        public void inputChange( float t, int i, boolean v ) {
            /** Simulation event service routine called
             *  when input i of this or gate changes at time t to value v.
             */

            boolean newValue = false;
            inputValue[i] = v;
            for (boolean vi: inputValue) if (vi) newValue = true;
           
            if (newValue != outputValue) {
                outputValue = newValue;
                Simulator.schedule(
                    t + delay,
                    (float time)
                           -> this.outputChange( time, outputValue )
                );
            }
        }
    }

    class NotGate extends Gate {
        private NotGate() {} // prevent outsiders from using the initializer
        private static List <String> inputs = Arrays.asList( "in" );

        public static Gate scan( Scanner sc ) {
            NotGate g = new NotGate();
            g.scan( sc, inputs );

            // tickle this gate so it triggers its initial event
            g.inputChange( 0, 0, false );

            if (g.name == null) g = null;
            return g;
        }

        public String toString() {
            /** Convert an intersection back to its textual description
             */
            return "gate not " + name + ' ' + delay;
        }

        public void inputChange( float t, int i, boolean v ) {
            /** Simulation event service routine called
             *  when input i of this not gate changes at time t to value v.
             */
           
            inputValue[i] = v;
            outputValue = !v;
            Simulator.schedule(
                t + delay,
                (float time) -> this.outputChange( time, outputValue )
            );
            outputValue = !v;
        }
    }

    public class LogicCircuit {
        /** Top level description of a logic circuit made of
             *  some gates connected by some wires.
         *  @see Gate
         *  @see Wire
         */
        static LinkedList <Gate> gates
            = new LinkedList <Gate> ();
        static LinkedList <Wire> wires
            = new LinkedList <Wire> ();

        static Gate findGate( String s ) {
            /** Given s the name of a particular gate
             *  returns null if that gate does not exist,
             *  returns that gate if it exists.
             *  @see Intersection
             */
            // Bug:  Reengineering this to use a hash should be possible
            for (Gate i: gates) {
                if (i.name.equals( s )) {
                    return i;
                }
            }
            return null;
        }

        private static void readCircuit( Scanner sc ) {
            /** Read a logic circuit, scanning its description from sc.
             */

            while (sc.hasNext()) {
                // until the input file is finished
                String command = sc.next();
                if ("gate".equals( command )) {
                    String kind = sc.next();
                    Gate g = null;
                    if ("and".equals( kind )) {
                        g = AndGate.scan( sc );
                    } else if ("or".equals( kind )) {
                        g = OrGate.scan( sc );
                    } else if ("not".equals( kind )) {
                        g = NotGate.scan( sc );
                    } else {
                        Errors.warn(
                            "gate '"
                            + kind
                            + "' type not supported"
                        );
                        sc.nextLine();
                    }
                    if (g != null) gates.add( g );
                } else if ("wire".equals( command )) {
                    Wire w = Wire.scan( sc );
                    if (w != null) wires.add( w );
                } else {
                    Errors.warn(
                        "'"
                        + command
                        + "' not a wire or gate"
                    );
                    sc.nextLine();
                }
            }
        }

        private static void checkCircuit() {
            /** Check the completeness of the logic circuit description.
             */
            for (Gate g: gates) {
                g.checkInputs();
            }
        }

        private static void writeCircuit() {
            /** Write out a textual description of the entire logic circuit.
             *  This routine is scaffolding used during development.
             */
            for (Gate g: gates) {
                System.out.println( g.toString() );
            }
            for (Wire w: wires) {
                System.out.println( w.toString() );
            }
        }

            public static void main(String[] args) {
            /** Create a logic circuit.
             *  The command line argument names the input file.
             *  For now, the output is just a reconstruction of the input.
             */
            if (args.length < 1) {
                Errors.fatal( "Missing filename argument" );
            }
            if (args.length > 1) {
                Errors.fatal( "Extra command-line arguments" );
            }
            try {
                    readCircuit( new Scanner( new File( args[0] )));
                    checkCircuit();
                writeCircuit();
                Simulator.run();
            } catch (FileNotFoundException e) {
                Errors.fatal( "Can't open file '" + args[0] + "'" );
            }
            }
    }// NeuronNetwork.java
    /** Java program to read and process a neuron network
     *
     * @version: April 6, 2016
     *
     * This code is based on NeuronNetwork.java, the non-alternative
     * solution to MP3, as well as a simulation framework from the
     * March 11 lecture notes. These were extended to solve MP4.
     */

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.LinkedList;
    import java.util.PriorityQueue;
    import java.util.regex.Pattern;
    import java.util.Scanner;
    import java.lang.Math;

    // Utility classes

    /** Error reporting methods
     */
    class Errors {
        public static int errCount = 0;
        public static void fatal( String message ) {
            errCount++;
            System.err.println( "Fatal error: " + message );
            System.exit( 1 );
        }
        public static void warning( String message ) {
            errCount++;
            System.err.println( "Error: " + message );
        }
    }

    /** Input scanning support methods
     */
    class ScanSupport {
        /** Interface allowing error messages passed as lambda expressions
         */
        public interface ErrorMessage {
            abstract String myString();
        }

        /** Force there to be a line end here, complain if not
         */
        static void lineEnd( Scanner sc, ErrorMessage message ) {
            String skip = sc.nextLine();
            if (!"".equals( skip )) {
                // Bug:  do we want to allow comments here
                Errors.warning(
                    message.myString() +
                    " -- expected a newline"
                );
            }
            // Bug:  should we allow comments here?
            // Bug:  what if sc.nextLine() was illegal (illegal state)
        }

        /* really private to nextName */
        private static final Pattern name = Pattern.compile( "[A-Za-z]\\w*" );

        /** Get the next float, or complain if there isn't one
         */
        static String nextName( Scanner sc, ErrorMessage message ) {
            if (sc.hasNext( name )) {
                return sc.next( name );
            } else {
                Errors.warning(
                    message.myString() +
                    " -- expected a name"
                );
                return null;
            }
        }

        /** Get the next float, or complain if there isn't one
         */
        static float nextFloat( Scanner sc, ErrorMessage message ) {
            if (sc.hasNextFloat()) {
                return sc.nextFloat();
            } else {
                Errors.warning(
                    message.myString() +
                    " -- expected a number"
                );
                return 99.99f;
            }
        }
    }

    // Simulation classes

    /** Framework for discrete event simulation.
     */
    class Simulator {

            public interface Action {
                    // actions contain the specific code of each event
                    void trigger( float time );
            }

            private static class Event {
                    public float time; // the time of this event
                    public Action act; // what to do at that time
            }

            private static PriorityQueue <Event> eventSet
            = new PriorityQueue <Event> (
                    (Event e1, Event e2) -> Float.compare( e1.time, e2.time )
            );

            /** Call schedule to make act happen at time.
             *  Users typically pass the action as a lambda expression:
             *  <PRE>
             *  Simulator.schedule(t,(float time)->method(params,time))
             *  </PRE>
             */
            static void schedule( float time, Action act ) {
                    Event e = new Event();
                    e.time = time;
                    e.act = act;
                    eventSet.add( e );
            }

            /** Call run() after scheduling some initial events
             *  to run the simulation.
             */
            static void run() {
                    while (!eventSet.isEmpty()) {
                            Event e = eventSet.remove();
                            e.act.trigger( e.time );
                    }
            }
    }


    /** Neurons are joined by synapses
     *  @see Synapse
     */
    class Neuron {
        String name;            // name of this neuron

        public static class IllegalNameEx extends Exception {}

        // default values below for errors with incompletely defined neurons
        private float threshold = 99.99f;// voltage at which the neuron fires
        private float voltage = 99.99f; // voltage at the given time
        private float time = 0.0f;  // (see above)

        // the outputs of this neuron
        public LinkedList <Synapse> synapses = new LinkedList<Synapse>();

        // initializer
        public Neuron( Scanner sc ) throws IllegalNameEx {
            // scan and process one neuron
            String name = ScanSupport.nextName(
                sc,
                () -> "Neuron ???"
            );
            if (name == null) { // nextName() already reported syntax error
                sc.nextLine();
                throw new IllegalNameEx ();
            }
            this.name = name;
            if ( (NeuronNetwork.findNeuron( name ) != null)
            ||   (NeuronNetwork.findSynapse( name ) != null) ) {
                Errors.warning(
                    "Neuron " + name +
                    " -- duplicate declaration"
                );
                sc.nextLine();
                throw new IllegalNameEx();
            }
            threshold = ScanSupport.nextFloat(
                sc,
                () -> Neuron.this.toString()
            );
            voltage = ScanSupport.nextFloat(
                sc,
                () -> Neuron.this.toString()
            );

            //  voltage must exceed threshold (non-inclusive)
            if (voltage > threshold){
                Simulator.schedule( 0.0f, (float t) -> this.fire(t) );
            }

            ScanSupport.lineEnd(
                sc,
                () -> Neuron.this.toString()
            );
        }

        // simulation methods
        void fire(float time) {
            System.out.println( time + " neuron " + name + " fired");
            this.voltage = 0.0f;
            for(Synapse s: synapses) {
                Simulator.schedule( time+s.delay, (float t) -> s.fire(t) );
            }
        }

        /** This method is called by incoming synapses. It returns the string
         *  describing how this neuron's voltage changed.
         */
        String kick(float time, float strength) {
            float v1 = voltage;
            // v2 = v1 e^(t1–t2) + s
            voltage = (v1 * (float)Math.exp( this.time - time )) + strength;
            this.time = time;
            if( voltage > threshold){
                // schedule this so we can return, and print the synapse firing
                // before we print the neuron firing in fire().
                Simulator.schedule( time, (float t) -> this.fire(t) );
            }
            return v1 +" "+ voltage;
        }

        // other methods
        public String toString() {
            return (
                "Neuron " +
                name +
                " " +
                threshold +
                " " +
                voltage
            );
        }
    }

    /** Synapses come in several flavors
     *  @see Neuron
     *  @see PrimarySynapse
     *  @see SecondarySynapse
     */
    abstract class Synapse {
        // default values below for errors with incompletely defined synapses
        Neuron source;          // source for this synapse
        Float delay = 99.99f;
        Float strength = 99.99f;
        String name = null;     // name of this synapse, if it has one

        public static class IllegalNameEx extends Exception {}

        // really private to Synapse initializer
        private static final Pattern noName = Pattern.compile( "-" );

        // generic initializer
        static Synapse newSynapse( Scanner sc ) throws IllegalNameEx {
            // proxies for fields until we know the type of this synapse
            String myName = null;
            Neuron mySource = null;

            // only one of the following proxies will be non-null
            Neuron myPrimaryDest = null;
            Synapse mySecondaryDest = null;

            // the Synapse we're allocating
            Synapse mySynapse = null;
           
            // scan and process one synapse
            if (sc.hasNext( noName )) { // unnamed synapse
                sc.next( noName );
            } else { // named synapse, process the name
                myName = ScanSupport.nextName(
                    sc,
                    () -> "Synapse ???"
                );
                if (myName == null) {
                    // nextName() already reported syntax error
                    sc.nextLine();
                    throw new IllegalNameEx ();
                }
                if ((NeuronNetwork.findNeuron( myName ) != null)
                ||  (NeuronNetwork.findSynapse( myName ) != null)) {
                    Errors.warning(
                        "Synapse " + myName +
                        " -- duplicate declaration"
                    );
                    sc.nextLine();
                    throw new IllegalNameEx();
                }
            }

            // the following is needed because of limits of java lambda
            final String finalName = myName;

            String sourceName = ScanSupport.nextName(
                sc,
                () -> (
                    "Synapse " +
                    (finalName != null ? finalName : "-") +
                    " ???"
                )
            );
            String dstName = ScanSupport.nextName(
                sc,
                () -> (
                    "Synapse " +
                    (finalName != null ? finalName : "-") +
                    " " +
                    (sourceName != null ? sourceName : "---") +
                    " ???"
                )
            );
            mySource = NeuronNetwork.findNeuron( sourceName );
            myPrimaryDest = NeuronNetwork.findNeuron( dstName );
            if (myPrimaryDest == null) {
                mySecondaryDest = NeuronNetwork.findSynapse( dstName );
                mySynapse = new SecondarySynapse( mySecondaryDest );
            } else {
                mySynapse = new PrimarySynapse( myPrimaryDest );
            }

            // the following is needed because of limits of java lambda
            final Synapse finalSynapse = mySynapse;

            finalSynapse.name = finalName;
            finalSynapse.source = mySource;
       
            finalSynapse.delay = ScanSupport.nextFloat(
                sc,
                () -> finalSynapse.toString()
            );
            finalSynapse.strength = ScanSupport.nextFloat(
                sc,
                () -> finalSynapse.toString()
            );
            ScanSupport.lineEnd(
                sc,
                () -> finalSynapse.toString()
            );

            // check correctness of fields
            if ((sourceName != null) && (mySource == null)) {
                Errors.warning(
                    finalSynapse.toString() +
                    " -- no such source"
                );
            }
            if ( (dstName != null)
            &&   (myPrimaryDest == null)
            &&   (mySecondaryDest == null) ) {
                Errors.warning(
                    finalSynapse.toString() +
                    " -- no such destination"
                );
            }
            if (finalSynapse.delay < 0.0f) {
                Errors.warning(
                    finalSynapse.toString() +
                    " -- illegal negative delay"
                );
                finalSynapse.delay = 99.99f;
            }
            if (finalSynapse != null && finalSynapse.source != null) {
                finalSynapse.source.synapses.add(finalSynapse);
            }
            return finalSynapse;
        }

        // simulation methods
        abstract void fire(float time);

        // other methods
        public abstract String toString();
    }

    /** Primary Synapses join neurons to neurons
     *  @see Neuron
     *  @see Synapse
     */
    class PrimarySynapse extends Synapse {
        Neuron destination;

        public PrimarySynapse( Neuron dst ) {
            // Called from Synapse.newSynapse() and nowhere else
            // All the field initialization and checking is done there,
            // except the following:
            destination = dst;
        }

        // simulation methods
        void fire(float time) {
            // the voltage of the destination before and after
            String change_str = destination.kick(time, this.strength);
            System.out.println(
                time +
                " synapse " +
                ( name != null ? name : "-" ) +
                " " +
                source.name + // note: source is never null during simulation
                " " +
                destination.name + // note: destination is never null as above
                " " +
                change_str
            );
        }

        // other methods
        public String toString() {
            return (
                "Synapse " +
                ( name != null ? name : "-" ) +
                " " +
                ( source != null ? source.name : "---" ) +
                " " +
                ( destination != null ? destination.name : "---" ) +
                " " + delay + " " + strength
            );
        }
    }

    /** Secondary synapses join neurons to primary synapses
     *  @see Neuron
     *  @see Synapse
     *  @see PrimarySynapse
     */
    class SecondarySynapse extends Synapse {
        PrimarySynapse destination;

        public SecondarySynapse( Synapse dst ) {
            // Called from Synapse.newSynapse() and nowhere else
            // All the field initialization and checking is done there,
            // except the following:

            if ( (dst != null)
            &&   (dst instanceof SecondarySynapse) ) {
                Errors.warning(
                    this.toString() +
                    " -- destination is a secondary synapse"
                );
                destination = null;
            } else {
                destination = (PrimarySynapse) dst;
            }
        }

        // simulation methods
        void fire(float time) {
            System.out.println(
                time +
                " synapse " +
                (name != null ? name : "-") +
                " " +
                source.name + // note: source is never null during simulation
                " " +
                destination.name + // note: destination is never null as above
                " " +
                destination.strength +
                " " +
                (destination.strength + this.strength)
            );
            destination.strength += this.strength;
        }

        // other methods
        public String toString() {
            return (
                "Synapse " +
                (name != null ? name : "-") +
                " " +
                ( source != null ? source.name : "---" ) +
                " " +
                ( destination != null ? destination.name : "---" ) +
                " " + delay + " " + strength
            );
        }
    }

    /** NeuronNetwork is the main class that builds the whole model
     *  @see Neuron
     *  @see Synapse
     */
    public class NeuronNetwork {

        // the sets of all neurons and synapses
        static LinkedList <Neuron> neurons
            = new LinkedList <Neuron> ();
        static LinkedList <Synapse> synapses
            = new LinkedList <Synapse> ();

        /** Look up s in neurons, find that Neuron if it exists
         *  return null if not.
         */
        public static Neuron findNeuron( String s ) {
            /* special case added because scan-support can return null */
            if (s == null) return null;

            /* search the neuron list */
            for (Neuron n: neurons) {
                if (n.name.equals(s)) {
                    return n;
                }
            }
            return null;
        }

        /** Look up s in synapses, find that Synapse if it exists
         *  return null if not.
         */
        public static Synapse findSynapse( String s ) {
            /* special case added because scan-support can return null */
            if (s == null) return null;

            /* search the synapse list */
            for (Synapse sy: synapses) {
                if ((sy.name != null) && (sy.name.equals(s))) {
                    return sy;
                }
            }
            return null;
        }

        /** Initialize the neuron network by scanning its description
         */
        static void initializeNetwork( Scanner sc ) {
            while (sc.hasNext()) {
                String command = sc.next();
                if ("neuron".equals( command )) {
                    try {
                        neurons.add( new Neuron( sc ) );
                    } catch (Neuron.IllegalNameEx e) {}
                } else if ("synapse".equals( command )) {
                    try {
                        synapses.add( Synapse.newSynapse(sc) );
                    } catch (Synapse.IllegalNameEx e) {}
                } else {
                    Errors.warning( command + " -- what is that" );
                    sc.nextLine();
                }
            }
        }

        /** Print out the neuron network from the data structure
         */
        static void printNetwork() {
            for (Neuron n:neurons) {
                System.out.println( n.toString() );
            }
            for (Synapse s:synapses) {
                System.out.println( s.toString() );
            }
        }

        /** Main program
         * @see initializeNetwork
         * @see printNetwork
         */
        public static void main(String[] args) {
            if (args.length < 1) {
                Errors.fatal( "missing file name" );
            }
            if (args.length > 1) {
                Errors.fatal( "too many arguments" );
            }
            try {
                initializeNetwork( new Scanner(new File(args[0])) );
            } catch (FileNotFoundException e) {
                Errors.fatal( "file not found: " + args[0] );
            }
            if (Errors.errCount == 0){
                Simulator.run();
            } else {
                printNetwork();
            }
        }/** TernaryLogic.java -- classes that describe a ternary logic system
     *   *  @version mp3, 2017-03-12
     *
     * 
     */

    import java.util.LinkedList;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import java.util.regex.Pattern;

    /** Utility package for error handling
     */
    class Errors {
        private Errors(){}; // you may never instantiate this class

        /** Call this to warn of non fatal errors
         */
        public static void warn( String message ) {
            System.err.println( "Warning: " + message );
        }

        /** Call this to report fatal errors
         */
        public static void fatal( String message ) {
            System.err.println( "Fatal error: " + message );
            System.exit( -1 );
        }
    }

    /** Utility package for more interesting scanner behaviors
     */
    class ScanSupport {

        /** Pattern for identifers
         */
        public static final Pattern name
            = Pattern.compile( "[a-zA-Z0-9_]*" );

        /** Pattern for whitespace excluding things like newline
         */
        public static final Pattern whitespace
            = Pattern.compile( "[ \t]*" );

        /** Get next name without skipping to next line (unlike sc.Next())
         *  @param sc the scanner from which end of line is scanned
         *  @return the name, if there was one, or an empty string
         */
        public static String nextName( Scanner sc ) {
            sc.skip( whitespace );

            // the following is weird code, it skips the name
            // and then returns the string that matched what was skipped
            sc.skip( name );
            return sc.match().group();
        }

        /** Advance to next line and complain if is junk at the line end
         *  @see Errors
         *  @param message gives a prefix to give context to error messages
         *  @param sc the scanner from which end of line is scanned
         */
        public static void lineEnd( Scanner sc, String message ) {
            sc.skip( whitespace );
            String lineEnd = sc.nextLine();
            if ( (!lineEnd.equals( "" ))
            &&   (!lineEnd.startsWith( "--" )) ) {
                Errors.warn(
                    message +
                    " followed unexpected by '" + lineEnd + "'"
                );
            }
        }
    }

    /** Wires link gates
     *  @see Gate
     *  @see Errors
     *  @see TernaryLogic#findGate(String)
     */
    class Wire {
        private final float delay;    // time delay of this wire
        private final Gate destination;    // where wire goes, or null
        private final Gate source;    // source of wire, or null
        // Wire name is the source-destination names

        /** initializer scans and processes one wire definition
         */
        public Wire( Scanner sc ) {
            // textual names of source and dest
            String srcName = ScanSupport.nextName( sc );
            String dstName = ScanSupport.nextName( sc );
            // if there are no next names on this line, these are ""
            // therefore, the findGate calls below will fail

            // lookup names of source and dest
            source = TernaryLogic.findGate( srcName );
            if (source == null) {
                Errors.warn(
                    "Wire '" + srcName +
                    "' '" + dstName +
                    "' source undefined."
                );
            }
            destination = TernaryLogic.findGate( dstName );
            if (destination == null) {
                Errors.warn(
                    "Wire '" + srcName +
                    "' '" + dstName +
                    "' destination undefined."
                );
            }

            if (sc.hasNextFloat()) {
                delay = sc.nextFloat();
                if (delay < 0.0f) {
                    Errors.warn(
                        "Wire '" + srcName +
                        "' '" + dstName +
                        "' '" + delay +
                        "' has negative delay."
                    );
                }
            } else {
                Errors.warn(
                    "Wire '" + srcName +
                    "' '" + dstName +
                    "' has no delay."
                );
                delay = 99.999f;
            }
            ScanSupport.lineEnd( sc, this.toString() );
        }

        /** output this wire in a format like that used for input
         */
        public String toString() {
            String srcName;
            String dstName;

            if (source == null) {
                srcName = "???";
            } else {
                srcName = source.name;
            }

            if (destination == null) {
                dstName = "???";
            } else {
                dstName = destination.name;
            }
           
            return(
                "wire " +
                srcName + " " +
                dstName + " " +
                delay
            );
        }
    }

    /** Gates are linked by wires
     *  @see Wire
     *  @see MinGate
     *  @see MaxGate
     *  @see NotGate
     *  @see IsTGate
     *  @see IsFGate
     *  @see IsUGate
     *  @see TernaryLogic#findGate(String)
     */
    abstract class Gate {
        private final LinkedList <Wire> outgoing = new LinkedList <Wire> ();
        // Bug:  Does the gate need a list of incoming wires?
        public final String name;    // the name of the gate

        // Gripe:  We'd like to declare the following as final, but can't
        // because they're set by the subclass constructor
        public       int    inputs;    // the type of the gate
        public       float  delay;    // the type of the gate

        /** constructor needed by subclasses to set the final fields of gate
         */
        protected Gate( String n ) {
            name = n;
        }

        /** factory method scans and processes one gate definition
         */
        public static Gate newGate( Scanner sc ) {
            String myName = ScanSupport.nextName( sc );
            if ("".equals( myName )) {
                Errors.warn(
                    "gate has no name"
                );
                sc.nextLine();
                return null;
            }

            if (TernaryLogic.findGate( myName ) != null) {
                Errors.warn(
                    "Gate '" + myName +
                    "' redefined."
                );
                sc.nextLine();
                return null;
            }

            String myType = ScanSupport.nextName( sc );
            if ("min".equals( myType )) {
                return new MinGate( sc, myName );

            } else if ("max".equals( myType )) {
                return new MaxGate( sc, myName );

            } else if ("neg".equals( myType )) {
                return new NegGate( sc, myName );

            } else if ("isfalse".equals( myType )) {
                return new IsFGate( sc, myName );

            } else if ("istrue".equals( myType )) {
                return new IsTGate( sc, myName );

            } else if ("isunknown".equals( myType )) {
                return new IsUGate( sc, myName );

            } else {
                Errors.warn(
                    "Gate '" + myName +
                    "' '" + myType +
                    "' has an illegal type."
                );
                sc.nextLine();
                return null;
            }
        }

        /** Scan gate's delay and line end to finish initialization;
         *  this is always called at the end of the subclass constructor
         */
        protected final void finishGate( Scanner sc ) {
            if (sc.hasNextFloat()) {
                delay = sc.nextFloat();
                if (delay < 0.0f) {
                    Errors.warn(
                        this.myString() +
                        " -- has negative delay."
                    );
                }
            } else {
                Errors.warn(
                    this.myString() + " -- has no delay"
                );
            }
            ScanSupport.lineEnd( sc, this.myString() );
        }

        /** output this Gate in a format like that used for input
         *  it would have been nice to use toString here, but can't protect it
         */
        protected String myString() {
            return(
                "gate " + name
            );
        }
    }

    /** MinGate a kind of Gate
     *  @see Gate
     */
    class MinGate extends Gate {
        /** initializer scans and processes one min gate
         *  @parame sc Scanner from which gate description is read
         *  @param myName the value to be put in the name field
         */
        MinGate( Scanner sc, String myName ) {
            // the text "gate myName min" has already been scanned
            super( myName );

            // get inputs
            if (sc.hasNextInt()) {
                inputs = sc.nextInt();
            } else {
                Errors.warn(
                    this.myString() +
                    " min -- has no input count"
                );
            }

            this.finishGate( sc );
        }

        /** output this Gate in a format like that used for input
         */
        public String toString() {
            return(
                this.myString() + " min " + inputs + " " + delay
            );
        }
    }

    /** MaxGate a kind of Gate
     *  @see Gate
     */
    class MaxGate extends Gate {
        /** initializer scans and processes one max gate
         *  @parame sc Scanner from which gate description is read
         *  @param myName the value to be put in the name field
         */
        MaxGate( Scanner sc, String myName ) {
            // the text "gate myName min" has already been scanned
            super( myName );

            // get inputs
            if (sc.hasNextInt()) {
                inputs = sc.nextInt();
            } else {
                Errors.warn(
                    this.myString() + " max -- has no input count"
                );
            }

            this.finishGate( sc );
        }

        /** output this Gate in a format like that used for input
         */
        public String toString() {
            return(
                this.myString() + " max " + inputs + " " + delay
            );
        }
    }

    /** NegGate a kind of Gate
     *  @see Gate
     */
    class NegGate extends Gate {
        /** initializer scans and processes one neg gate
         *  @parame sc Scanner from which gate description is read
         *  @param myName the value to be put in the name field
         */
        NegGate( Scanner sc, String myName ) {
            // the text "gate myName min" has already been scanned
            super( myName );

            inputs = 1; // it is a one-input gate

            this.finishGate( sc );
        }

        /** output this Gate in a format like that used for input
         */
        public String toString() {
            return(
                this.myString() + " neg " + " " + delay
            );
        }
    }

    /** IsTGate a kind of Gate
     *  @see Gate
     */
    class IsTGate extends Gate {
        /** initializer scans and processes one neg gate
         *  @parame sc Scanner from which gate description is read
         *  @param myName the value to be put in the name field
         */
        IsTGate( Scanner sc, String myName ) {
            // the text "gate myName min" has already been scanned
            super( myName );

            inputs = 1; // it is a one-input gate

            this.finishGate( sc );
        }

        /** output this Gate in a format like that used for input
         */
        public String toString() {
            return(
                this.myString() + " istrue " + delay
            );
        }
    }

    /** IsFGate a kind of Gate
     *  @see Gate
     */
    class IsFGate extends Gate {
        /** initializer scans and processes one neg gate
         *  @parame sc Scanner from which gate description is read
         *  @param myName the value to be put in the name field
         */
        IsFGate( Scanner sc, String myName ) {
            // the text "gate myName min" has already been scanned
            super( myName );

            inputs = 1; // it is a one-input gate

            this.finishGate( sc );
        }

        /** output this Gate in a format like that used for input
         */
        public String toString() {
            return(
                this.myString() + " isfalse " + delay
            );
        }
    }

    /** IsUGate a kind of Gate
     *  @see Gate
     */
    class IsUGate extends Gate {
        /** initializer scans and processes one neg gate
         *  @parame sc Scanner from which gate description is read
         *  @param myName the value to be put in the name field
         */
        IsUGate( Scanner sc, String myName ) {
            // the text "gate myName min" has already been scanned
            super( myName );

            inputs = 1; // it is a one-input gate

            this.finishGate( sc );
        }

        /** output this Gate in a format like that used for input
         */
        public String toString() {
            return(
                this.myString() + " isundefined " + delay
            );
        }
    }

    /** TernaryLogic -- main program that reads and writes a ternary logic system
     *  @see Wire
     *  @see Gate
     *  @see Errors
     *  @see #main
     */
    public class TernaryLogic {
        // lists of roads and intersectins
        static LinkedList <Wire> wires
            = new LinkedList <Wire> ();
        static LinkedList <Gate> gates
            = new LinkedList <Gate> ();

        /** utility method to look up an gate by name
         *  @param s is the name of the gate, a string
         *  @return is the Gate object with that name
         */
        public static Gate findGate( String s ) {
            for ( Gate g: gates ) {
                if (g.name.equals( s )) return g;
            }
            return null;
        }

        /** read a ternary logic system
         */
        public static void initializeTernary( Scanner sc ) {
            while (sc.hasNext()) {
                // until we hit the end of the file
                String command = ScanSupport.nextName( sc );
                if ("gate".equals( command )) {
                    Gate g = Gate.newGate( sc );
                    if (g != null) gates.add( g );

                } else if ("wire".equals( command )) {
                    wires.add( new Wire( sc ) );

                } else if ("".equals( command )) { // blank or comment
                    // line holding -- ends up here!
                    ScanSupport.lineEnd( sc, "Line" );

                } else {
                    Errors.warn(
                        "Command '" + command +
                        "' is not gate or wire"
                    );
                    sc.nextLine(); // skip the rest of the error
                }
            }
        }

        /** write out a ternary logic system
         */
        public static void writeTernary() {
            for ( Gate g: gates ) {
                System.out.println( g.toString() );
            }
            for ( Wire w: wires ) {
                System.out.println( w.toString() );
            }
        }

        /** main program that reads and writes a road network
         *  @param args the command line arguments must hold one file name
         */
        public static void main( String[] args ) {
            // verify that the argument exists.
            if (args.length < 1) {
                Errors.fatal( "Missing file name on command line" );

            } else if (args.length > 1) {
                Errors.fatal( "Unexpected command line args" );

            } else try {
                initializeTernary( new Scanner( new File( args[0] ) ) );
                writeTernary();

            } catch (FileNotFoundException e) {
                Errors.fatal( "Could not read '" + args[0] + "'" );
            }
        }
    }
    }

Answers

(5)
Status NEW Posted 05 Jan 2018 02:01 PM My Price 10.00

-----------  ----------- H-----------ell-----------o S-----------ir/-----------Mad-----------am ----------- Th-----------ank----------- yo-----------u f-----------or -----------you-----------r i-----------nte-----------res-----------t a-----------nd -----------buy-----------ing----------- my----------- po-----------ste-----------d s-----------olu-----------tio-----------n. -----------Ple-----------ase----------- pi-----------ng -----------me -----------on -----------cha-----------t I----------- am----------- on-----------lin-----------e o-----------r i-----------nbo-----------x m-----------e a----------- me-----------ssa-----------ge -----------I w-----------ill----------- be----------- qu-----------ick-----------ly

Not Rated(0)