示例#1
0
 def partitionToPlacements(self, allFlights):
     pHash = dict()
     for f in allFlights:
         if f.getPlacementToken() in pHash.keys():
             p = pHash[f.getPlacementToken()]
             p.addFlight(f)
         else:
             nfp = FlightPlan([])
             pHash.update({
                 f.getPlacementToken():
                 Placement.Placement(f.getPlacementToken(), nfp)
             })
             nfp.addFlight(f)
     return list(pHash.values())
示例#2
0
    def runCLISim(self, args):
        if len(args) < 4:  # if (args.length < 4)
            print(ParameterCore.ParameterCore().USAGE
                  )  # System.out.println(ParameterCore.USAGE);
            print(
                "Argument Error: There must be 4 arguments."
            )  # System.err.println("Argument Error: There must be 4 arguments.");
            exit()  # System.exit(1);
        else:
            # try:
            self.control = args[0]  # control        		= args[0];
            self.waterfallSizeLimit = int(
                args[1])  # waterfallSizeLimit   = Integer.valueOf(args[1]);
            self.inFileName = args[2]  # inFileName     		= args[2];
            self.outFileName = args[3]  # outFileName    		= args[3];
            self.allFlights = None  # List<Flight> allFlights 	  		= null;
            self.allPlacements = None  # List<Placement> allPlacements    = null;

            # except Exception as e:  # System.err.println("\nArgument Error: " + e.getMessage() + " "
            #     print("\nArgument Error: " + str(e))  # + e.getLocalizedMessage() + " " + e.getCause());
            #     exit()

            # try:
            self.allFlights = Utils.Utils().readFlightsCSV(
                ParameterCore.ParameterCore().csv, self.inFileName
            )  # allFlights = Utils.readFlightsCSV(ParameterCore.csv, inFileName);
            # except Exception as e:
            #     print(
            #     "Error reading from file: " + self.inFileName)  # System.out.println("Error reading from file: " + inFileName);
            #     print(
            #     "\nInput File Error: " + str(e))  # System.err.println("\nInput File Error: " + e.getMessage() + " "
            #     exit()  # + e.getLocalizedMessage() + " " + e.getCause());
            # e.printStackTrace();"""
            ### Preprocess input data START ###
            # Preprocess each flight plan. This fills in missing data items.
        Utils.Utils().preProcessFlights(self.allFlights)
        # Partition flights into Placements.
        self.allPlacements = Utils.Utils().partitionToPlacements(
            self.allFlights)
        # Lexicographic sort Placements.
        #print(type(self.allPlacements))
        self.insertionSort(self.allPlacements)
        ### Preprocess input data END ###

        cityCount = 0  # int cityCount = 0;
        tMax = 0  # double tMax = 0;
        packs = dict(
        )  # HashMap<Integer,RunData> packs = new HashMap<Integer,RunData> ();

        for p in self.allPlacements:  # for (Placement p: allPlacements){
            packs.clear()  # packs.clear(); ##is this necessary?
            for j in range(-1,
                           p.getFp().size()
                           ):  # for (int j = -1; j < p.getFp().size(); j + +){
                pack = RunData()  # RunData pack = new RunData();
                pack.window = j  # pack.window = j;
                packs.update({j: pack})  # packs.put(j, pack);

                maxWindow = 5  # Integer maxWindow = 5;//p.getFp().size();
                drawStore = dict(
                )  # HashMap<String, Double[]> drawStore = new HashMap<String, Double[]>();
                for j in range(
                        -1,
                        maxWindow):  # for ( int j=-1; j < maxWindow; j++ ){
                    if j > -1:  # if( j > -1 )
                        Utils.Utils().optimizePlacement(
                            2147483647, self.control, p
                        )  # Utils.optimizePlacement(Integer.MAX_VALUE, control, p);
                    else:
                        Utils.Utils().optimizePlacement(
                            2147483647, self.control, p
                        )  # Utils.optimizePlacement(Integer.MAX_VALUE, control, p);
                        if p.getFp().size() > 3:
                            random.shuffle(
                                p.getFp().getAsList()[2:p.getFp().size()]
                            )  # Collections.shuffle( p.getFp().getAsList().subList(2, p.getFp().size()) )

                    rewards = [
                    ]  # ArrayList<Double> rewards = new ArrayList<Double> ();
                    visitsBeforeFailure = [
                    ]  # ArrayList<Integer> visitsBeforeFailure = new ArrayList<Integer> ();
                    visitsBeforeSuccess = [
                    ]  # ArrayList<Integer> visitsBeforeSuccess = new ArrayList<Integer> ();
                    pathLengthBeforeFailure = [
                    ]  # ArrayList<Double> pathLengthBeforeFailure = new ArrayList<Double> ();
                    pathLengthBeforeSuccess = [
                    ]  # ArrayList<Double> pathLengthBeforeSuccess = new ArrayList<Double> ();
                    timeAtLastFailure = [
                    ]  # ArrayList<Double> timeAtLastFailure = new ArrayList<Double> ();
                    timeAtLastSuccess = [
                    ]  # ArrayList<Double> timeAtLastSuccess = new ArrayList<Double> ();
                    failureCount = 0  # Integer failureCount = 0;
                    successCount = 0  # Integer successCount = 0;

                    for i in range(
                            0, self.waterfallSizeLimit
                    ):  # for (int i=0; i<waterfallSizeLimit; i++)
                        cityCount = p.getFp().size(
                        )  # cityCount = p.getFp().size();
                        tMax = p.getFp().getAsList()[0].getTimeMax(
                        )  # tMax = p.getFp().getAsList().get(0).getTimeMax();
                        myPlan = p.getFp().cloneFlightPlan(
                        )  # FlightPlan myPlan = p.getFp().cloneFlightPlan();
                        myTrip = [
                        ]  # ArrayList<String> myTrip = new ArrayList<String> ( );
                        timeRemain = myPlan.getAsList()[0].getTimeMax(
                        )  # double timeRemain = myPlan.getAsList().get(0).getTimeMax();
                        timeMax = myPlan.getAsList()[0].getTimeMax(
                        )  # double timeMax = myPlan.getAsList().get(0).getTimeMax();

                        doStop = False  # boolean doStop = false;
                        while not doStop:  # while( !doStop )
                            myL = ''  # String myL = "";
                            for f in myPlan.getAsList(
                            ):  # for (Flight f : myPlan)
                                myL += str(f.getFid()
                                           ) + ' '  # myL += f.getFid() + " ";

                            front = myPlan.getAsList(
                            )[1:]  # Flight front = myPlan.getAsList().remove( 0 );
                            try:
                                key = front[i].getFid(
                                ) + i  # String key = front.getFid() + i;             ############################ key = front.getFid() + i
                            except IndexError:
                                pass
                            testArr = None  # Double testArr[] = null;
                            if key in drawStore.keys(
                            ):  # if ( drawStore.containsKey(key) )
                                testArr = drawStore[
                                    key]  # testArr = drawStore.get(key);
                            else:
                                testArr = self.simRun(
                                    front[i]
                                )  # testArr = simRun( front );                     ################ testArr = self.simRun(front)
                                drawStore.update(
                                    {key:
                                     testArr})  # drawStore.put(key, testArr);

                            prevTime = timeRemain  # double prevTime = timeRemain;
                            timeRemain -= testArr[
                                1]  # timeRemain -= testArr[1];

                            try:
                                myTrip.append(front[i].getFid(
                                ))  # myTrip.add( front.getFid() );
                            except IndexError:
                                pass

                            if testArr[
                                    0] > 0.0 and timeRemain >= 0.0:  # if ( testArr[0] > 0.0 && timeRemain >= 0.0 )
                                rewards.append(
                                    testArr[0])  # rewards.add( testArr[0] );
                                visitsBeforeSuccess.append(
                                    len(myTrip)
                                )  # visitsBeforeSuccess.add( myTrip.size() );
                                pathLengthBeforeSuccess.append(
                                    timeMax - timeRemain
                                )  # pathLengthBeforeSuccess.add( timeMax - timeRemain );
                                timeAtLastSuccess.append(
                                    prevTime
                                )  # timeAtLastSuccess.add( prevTime );
                                successCount += 1  # successCount += 1;
                                doStop = True  # doStop = true;
                                break

                            elif myPlan.size(
                            ) < 1 or timeRemain <= 0.0:  # else if ( myPlan.size() < 1 || timeRemain <= 0.0 )
                                rewards.append(0.0)  # rewards.add( 0.0 );
                                visitsBeforeFailure.append(
                                    len(myTrip)
                                )  # visitsBeforeFailure.add( myTrip.size() );
                                pathLengthBeforeFailure.append(
                                    timeMax - timeRemain
                                )  # pathLengthBeforeFailure.add( timeMax - timeRemain );
                                timeAtLastFailure.append(
                                    prevTime
                                )  # timeAtLastFailure.add( prevTime );
                                failureCount += 1  # failureCount += 1;
                                doStop = True  # doStop = true;
                                break

                            if not doStop:  # if ( !doStop )
                                for f in myPlan.getAsList(
                                ):  # for( Flight f : myPlan )
                                    f.setTimeMax(
                                        timeRemain
                                    )  # f.setTimeMax( timeRemain )

                                if j > 0:  # if ( j > 0 )
                                    temp = Placement.Placement(
                                        front[i].getPlacementToken(),
                                        myPlan.cloneFlightPlan()
                                    )  # Placement temp = new Placement( front.getPlacementToken(), myPlan.cloneFlightPlan() );
                                    Utils.Utils().optimizePlacement(
                                        j, "b", temp
                                    )  # Utils.optimizePlacement( j, "b", temp );
                                    best = temp.getFp(
                                    )[0]  # Flight best = temp.getFp().get(0);
                                    myPlan.getAsList().remove(
                                        best
                                    )  # myPlan.getAsList().remove(best);
                                    myPlan.getAsList().insert(
                                        0, best
                                    )  # myPlan.getAsList().add(0, best);

                        myL = ""  # String myL = "";
                        for s in myTrip:  # for (String s : myTrip)
                            myL += str(s) + " "  # myL += s + " ";
                        fname = self.inFileName[(
                            self.inFileName.rfind('/') + 1
                        ):len(
                            self.inFileName
                        )]  # String fname = inFileName.substring(inFileName.lastIndexOf('/') + 1, inFileName.length());

                    print("aa", packs)
                    print(packs[j])
                    rd = packs[j]  # RunData rd = packs.get(j);
                    rd.averageReward = self.calculateAverage(
                        rewards
                    )  # rd.averageReward = calculateAverage( rewards );
                    rd.averagePathLengthBeforeFailure = self.calculateAverage(
                        pathLengthBeforeFailure
                    )  # rd.averagePathLengthBeforeFailure = calculateAverage( pathLengthBeforeFailure );
                    rd.averagePathLengthBeforeSuccess = self.calculateAverage(
                        pathLengthBeforeSuccess
                    )  # rd.averagePathLengthBeforeSuccess = calculateAverage( pathLengthBeforeSuccess );
                    rd.averageTimeAtLastFail = self.calculateAverage(
                        timeAtLastFailure
                    )  # rd.averageTimeAtLastFail = calculateAverage( timeAtLastFailure );
                    rd.averageTimeAtLastSuccess = self.calculateAverage(
                        timeAtLastSuccess
                    )  # rd.averageTimeAtLastSuccess = calculateAverage( timeAtLastSuccess );
                    rd.averageVisitsBeforeFailure = self.calculateAverage(
                        visitsBeforeFailure
                    )  # rd.averageVisitsBeforeFailure = calculateAverage2( visitsBeforeFailure );
                    rd.averageVisitsBeforeSuccess = self.calculateAverage(
                        visitsBeforeSuccess
                    )  # rd.averageVisitsBeforeSuccess = calculateAverage2( visitsBeforeSuccess );
                    rd.failCount = failureCount  # rd.failCount = failureCount;
                    rd.successCount = successCount  # rd.successCount = successCount;

                    # for avg in rewards:
                    #      print("REW" + avg)                                                             # System.out.println("REW " + avg);
                    fname = self.inFileName[(
                        self.inFileName.rfind('/') + 1
                    ):len(
                        self.inFileName
                    )]  # String fname = inFileName.substring( inFileName.lastIndexOf('/') + 1, inFileName.length() );
                    outS = ""  # String outS = "";
                    outS += str(fname) + "," + str(
                        rd.toString())  # outS += fname + "," + rd ;

                    #try:                                                                            # try:
                    with open(
                            "result.txt", "w+"
                    ) as out:  # PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outFileName, true)));
                        out.write(outS)  # out.println( outS );
                        out.flush()  # out.flush();
                        out.close()  # out.close();
                        print(outS)  # System.out.println( outS );
示例#3
0
class Interaction:

    def __init__(self, invent, location):
        """Sets up the inventory"""
        self.invent=invent
        self.location=location
        self.drop=Placement(location)
    
    def use(self, object):
        """Allows the user to use items they have picked up"""
        if self.invent[object]==1:
            if object=="nerfgun":
                if self.invent["bullets"]==1:
                    print "You load the nerfgun."
                    self.invent["loaded nerfgun"]+=1
                    self.invent["bullets"]+=1
                    self.invent["nerfgun"]+=1
                    return 1
                elif self.invent["bullets"]==0:
                    print "You realize that the nerfgun is empty and essentially useless."
                    return 0
                else:
                    print "You have already loaded the nerfgun."
                    return 0
            if object=="bullets":
                if self.invent['nerfgun']==0:
                    print "You don't have anything to use the bullets with."
                    return 0
                elif self.invent["nerfgun"]==1:
                    print "You load the nerfgun."
                    self.invent["loaded nerfgun"]+=1
                    self.invent["bullets"]+=1
                    self.invent["nerfgun"]+=1
                    return 1
                else:
                    print "You have already loaded the nerfgun."
                    return 0
            if object=="key":
                print "You can' seem to find anything that this key will unlock."
                print "This is the red key..."
                return 0
            else:
                print "You use the " +object+"."
                return 0
        if self.invent[object]==0:
            if object=="panal":
                if self.invent["lamp"]==1:
                    print "You hear some sounds coming from the roof."
                    print "You should go and check it out."
                    self.location["door2"]+=1
                    return 1
        else:
            print "Do what with what?"
            return 0
    def inventory(self):
        """Will display the users inventory"""
        for item in self.invent.keys():
            if self.invent[item] == 1:
                print item


    def take(self, object):
        ##add rooms for objects, not just accessable anywhere
        """Allows the user to take items from their environment"""
        if self.invent.has_key(object):
            if self.invent[object]==0:
                test=self.drop.place(object)
                if test==True:
                    self.invent[object]+=1
                    print "You take "+object+"."
                    if object=="painting":
                        print "You try to take it off the wall, but as soon as you get closer"
                        print "you are so repulsed by the painting that it forces you to back away"
                        return 0
                    if object=="lamp":
                        print "You decide to turn it on, since a lamp that is off is kinda useless."
                        return 0
                    else:
                        return 1
                else:
                    print "There is nothing like that here."
                    return 0
            
            if object=="mail":
                print "You check your mail box, doesn't look like the mail staff"
                print "was willing to fight through the zombies to get to Cro today."
                return 0
            else:
                print "You already have that."
                return 0
        
            
        else:
            print "There isn't anything like that here."
            return 0
        
    def open(self, object):
        """used to open doors and allow access to new rooms"""
        if self.location["NS"]==1 and self.location["EW"]==1 and self.location["UD"]==0:
            if object=="door":
                print "You open the door and zombies come puring in and eat your BRAINZ!!!!"
                print "OH NO!!!"
                print ""
                print ""
                print "ha ha"
                print "Just kidding, why would there be zombies in the basement?"
                self.location["door"]+=1
                return 1
        else:
            print "You don't see any closed doors around here."
            return 0

    def kill(self, object):
        if object=="zombie":
            if self.invent["loaded nerfgun"]==1:
                if self.location["NS"]==2 and self.location["EW"]==-2 and self.location["UD"]==-1:
                    print "You slowly sneak up on the zombie, nerfgun at the ready.  You c**k it"
                    print "and prepare to fire.  As you reach for the trigger it turns around and"
                    print "notices you.  You freeze as it charges you. At the last second you"
                    print "gain control of your hand again and closing your eyes you pull the"
                    print "trigger."
                    print ""
                    print "You open your eyes and the zombie lays dead on the floor, a perfect"
                    print "headshot.  Way to go you."
                    self.location["zombie"]+=1
                    return 1
                else:
                    print "There are no zombie here."
                    print "You are safe for now."
                    return 0
            else:
                print "You don't have anything to kill a zombie with."
                print "You need a projectile device, some ammunition, and to load the darn thing."
                return 0
        else:
            print "Sorry, I can't let you kill that."
            return 0

    def read(self, object):
        if object=="book":
            if self.invent["book"]==1:
                print "The title of the book is 'The Zombie Survival Guide', by Max Brooks."
                print "You skim through the book to see if any of it will be helpful."
                print "You find a chapter all about the most efficient ways to kill zombies."
                print "Your knowledge of the world has expanded."
                return 1

        elif object=="flyer":
            if self.invent["flyer"]==1:
                print "ConnQuest was designed and coded by Maxwell Alexander Novak,"
                print "with guidance from Paul Novak and Bridget Baird."
                print "Game Testers include:"
                print "Dann Goldman"
                print "Caroline Mills"
                print "Copyright 2010"
                return 1

        else:
            print "That is not readable, sorry."
            return 0
            
    def eat(self,object):
        if object=="fries":
            if self.invent["fries"]==1:
                print "You eat the curly fries. Yum!"
                print "You feel more energized."
                self.invent["fries"]+=1
                return 1
            else:
                print "You don't have that on your person."
                return 0
        elif object=="pie":
            print "You pull a slice of pie out your pocket dimension and eat it."
            pie=randrange(0,6)
            if pie == 0:
                print "It is apple."
            if pie == 1:
                print "It is blueberry."
            if pie == 2:
                print "It is chocolate cream."
            if pie == 3:
                print "It is strawberry."
            if pie == 4:
                print "It is banana cream."
            if pie == 5:
                print "It is peacan."
            print "YUM!"
            return 0
        else:
            print "Sorry, that isn't edible or you are allergic to it "
            print "or something like that."
            return 0
示例#4
0
 def __init__(self, invent, location):
     """Sets up the inventory"""
     self.invent=invent
     self.location=location
     self.drop=Placement(location)
示例#5
0
def SourceTest():
    s = Source("test", Placement([0, 0, 0], [0, 0, 1]))
    s.exampleRays(0.04)
    return s
示例#6
0
def SystemTest():
    print "System:SystemTest>"

    # source
    ppos = [0, 0, 0]
    pdir = [0, 0, 1]
    s0 = Source("light source", Placement(ppos, pdir))
    s0.exampleRays(0.04)

    # curved surface
    ppos = [0, 0, 0.05]
    pdir = [0, 0, 1]
    pdim = [0.05, 0.05, 0.01]
    s1 = SphericalSurface("spherical 1", Volume.circ, pdim,
                          Placement(ppos, pdir),
                          Material(Material.refract, 1.4), 0.08)

    # plane surface
    ppos = [0, 0, 0.07]
    pdir = [0, 0, 1]
    pdim = [0.05, 0.05, 0.01]
    s2 = PlaneSurface("plane 1", Volume.circ, pdim, Placement(ppos, pdir),
                      Material(Material.refract, 1.0))

    # plane surface
    ppos = [0, 0, 0.40]
    pdir = [0, 0, 1]
    pdim = [0.05, 0.05, 0.01]
    s3 = PlaneSurface("plane 2", Volume.circ, pdim, Placement(ppos, pdir),
                      Material(Material.refract, 1.4))

    # curved surface
    ppos = [0, 0, 0.42]
    pdir = [0, 0, 1]
    pdim = [0.05, 0.05, 0.01]
    s4 = SphericalSurface("spherical 2", Volume.circ, pdim,
                          Placement(ppos, pdir),
                          Material(Material.refract, 1.0), -0.08)

    # plane surface
    ppos = [0, 0, 0.50]
    pdir = pl.array([0, -1, 1])
    pdir = pdir / pl.linalg.norm(pdir)
    pdim = [0.05, 0.05, 0.01]
    s5 = PlaneSurface("plane 3", Volume.circ, pdim, Placement(ppos, pdir),
                      Material(Material.mirror, 1.0))

    # plane surface
    ppos = [0, 0.15, 0.50]
    pdir = [0, 1, 0]
    pdim = [0.05, 0.05, 0.01]
    s6 = PlaneSurface("plane 4", Volume.circ, pdim, Placement(ppos, pdir),
                      Material(Material.refract, 1.0))

    # system
    s = System()
    s.append(s0)
    s.append(s1)
    s.append(s2)
    s.append(s3)
    s.append(s4)
    s.append(s5)
    s.append(s6)

    return s

    # ray trace through system
    #    rl = s.propagate()
    #
    #    while r != None :
    #        rl.append(r)
    #        r1 = s[1].propagate(s[0],r)
    #        print r
    #        print r1[0]
    #        r = s[0].nextRay()
    #
    #    d = Display3D(s,rl)
    #    d.Draw()

    return s