Beispiel #1
0
    def __init__(self, argv, base=None):
        """
        main method
        @param argv: values of inline arguments
        """

        if (base == None):
            path = __file__.split('/')
            base = '/'.join(path[:-1]) + '/'

        CommandLineUI.__init__(self, 'swaml', base)

        self.config = Configuration()

        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--version":
                self.version()

        self.config.setAgent(
            'http://swaml.berlios.de/doap.rdf')  #TODO: how __init__.__agent__?
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), 'messages procesed'
Beispiel #2
0
def main():

    arguments = create_arguments()

    if arguments['configure'] != None:
        Configuration.create_configurations()
        print(colored("Success:", color='green'),
              "Configuration template was created")
        exit(0)

    if __validate_arguments__(arguments):
        if arguments['service'] == 'google':
            print("google")
            google_chat = GoogleChat(room=str(arguments['room']),
                                     text=str(arguments['text']))

            google_chat.perform()

        elif arguments['service'] == 'slack':

            slack_service = None

            if arguments['icon'] != None:
                slack_service = Slack(room=arguments['room'],
                                      text=arguments['text'],
                                      icon=str(arguments['icon']))
            else:
                slack_service = Slack(room=arguments['room'],
                                      text=arguments['text'],
                                      icon='ghost')

            slack_service.perform()

        elif arguments['service'] == 'rocket':
            print("rocket")

        elif arguments['service'] == 'twitter':
            if 'direct_message' in arguments and arguments['direct_message']:
                print(f"Send on dm: {arguments['direct_message']}")
            print("twitter")

        elif arguments['service'] == 'telegram':
            print("telegram")

        else:
            print(
                colored(f"Error:", color='red'),
                f"Invalid value '{arguments['service']}' for parameter SERVICE"
            )
            print(
                colored(f"Warning:", color='yellow'),
                "Possible values are => google, slack, telegram and twitter")
    else:
        print(colored(f"Error:", color='red'), f"Arguments are not valid")
        print(colored(f"Usage:", color='yellow'), f"{APP_NAME} -h")
Beispiel #3
0
 def __init__(self, argv):
     """
     main method
     @param argv: values of inline arguments
     """
     
     self.config = Configuration()
     self.config.setAgent(__url__)
     self.parseArgs(argv)
     self.list = MailingList(self.config)
     messages = self.list.publish()
     print str(messages), 'messages procesed'
Beispiel #4
0
class SWAML(CommandLineUI):
    """
    Main class of SWAML project
    
    @author: Sergio Fdez
    @license: GPL
    """

    def parseArgs(self, argv):
        """
        Getting params of default input
        
        @param argv: arguments values array
        """
        
        if not self.config.parse(argv):
            self.usage()
            
        #self.config.show()
        
    def version(self):
        print "SWAML 0.0.5", #TODO: __init__.__version__
        sys.exit()

    def __init__(self, argv, base=None):
        """
        main method
        @param argv: values of inline arguments
        """
        
        if (base == None):
            path = __file__.split('/')
            base = '/'.join(path[:-1]) + '/'
        
        CommandLineUI.__init__(self, 'swaml', base)
        
        self.config = Configuration()        
        
        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--version":
                self.version()
                
        self.config.setAgent('http://swaml.berlios.de/doap.rdf') #TODO: how __init__.__agent__?
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), 'messages procesed'
Beispiel #5
0
class SWAML(CommandLineUI):
    """
    Main class of SWAML project
    
    @author: Sergio Fdez
    @license: GPL
    """
    def parseArgs(self, argv):
        """
        Getting params of default input
        
        @param argv: arguments values array
        """

        if not self.config.parse(argv):
            self.usage()

        #self.config.show()

    def version(self):
        print "SWAML 0.0.5",  #TODO: __init__.__version__
        sys.exit()

    def __init__(self, argv, base=None):
        """
        main method
        @param argv: values of inline arguments
        """

        if (base == None):
            path = __file__.split('/')
            base = '/'.join(path[:-1]) + '/'

        CommandLineUI.__init__(self, 'swaml', base)

        self.config = Configuration()

        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--version":
                self.version()

        self.config.setAgent(
            'http://swaml.berlios.de/doap.rdf')  #TODO: how __init__.__agent__?
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), 'messages procesed'
Beispiel #6
0
    def requestData(self):
        """
        Queries the user a new configuration
        """

        self.config = Configuration()

        print 'Write your configuration options:'
        print '(default value goes between [...])'

        for var in self.config.config.keys():
            defaultValue = str(self.config.config[var])
            value = raw_input('\t - ' + var + '[' + defaultValue + ']: ')
            if (len(value) > 0):
                self.config.set(var, value)
Beispiel #7
0
 def __init__(self, argv, base=None):
     """
     main method
     @param argv: values of inline arguments
     """
     
     if (base == None):
         path = __file__.split('/')
         base = '/'.join(path[:-1]) + '/'
     
     CommandLineUI.__init__(self, 'swaml', base)
     
     self.config = Configuration()        
     
     for arg in argv:
         if arg == "-h" or arg == "--help":
             self.usage()
         elif arg == "-v" or arg == "--version":
             self.version()
             
     self.config.setAgent('http://swaml.berlios.de/doap.rdf') #TODO: how __init__.__agent__?
     self.parseArgs(argv)
     self.list = MailingList(self.config)
     messages = self.list.publish()
     print str(messages), 'messages procesed'
Beispiel #8
0
 def __init__(self, district_id):
     if district_id == 1:
         self.district = district_1
     elif district_id == 2:
         self.district = district_2
     elif district_id == 3:
         self.district = district_3
     elif district_id == 4:
         self.district = district_4
     else:
         return False
     self.world = Configuration(district_id)
     self.batteries = self.district["batteries"]
     self.houses = self.district["houses"]
     self.costs = 0
     self.violation = 0
Beispiel #9
0
 def __init__(self, district_id):
     if district_id == 1:
         self.district = district_1
     elif district_id == 2:
         self.district = district_2
     elif district_id == 3:
         self.district = district_3
     elif district_id == 4:
         self.district = district_4
     else:
         return False
     self.batteries = []
     self.world = Configuration(district_id)
     lists = self.world.get_lists()
     for battery0 in lists[0]:
         self.batteries.append(battery0[2])
     self.houses = self.district["houses"]
     self.costs = 0
class ConfigWizard(CommandLineUI):
    """
    SWAML's config wizard
    
    @author: Sergio Fdez
    @license: GPL
    """
    
    def requestData(self):
        """
        Queries the user a new configuration
        """
        
        self.config = Configuration()
        
        print 'Write your configuration options:'
        print '(default value goes between [...])'
        
        for var in self.config.config.keys():
            defaultValue = str(self.config.config[var])
            value = raw_input('\t - ' + var + '[' + defaultValue + ']: ')
            if (len(value) > 0):
                self.config.set(var, value)
    
    def printData(self):
        """
        Dump on hard disk the configuration
        """
        
        ini = ConfigParser.ConfigParser()
        
        ini.add_section(self.section)
        
        for var in self.config.config.keys():
            ini.set(self.section, var, str(self.config.config[var]))
                     
        try:
            file = open(self.output, 'w+')
            ini.write(file)
            file.flush()
            file.close()
            print 'new config file created in', self.output, 'with chosen parameters'
        except IOError, detail:
            print 'Error exporting coordinates config file: ' + str(detail)
Beispiel #11
0
    def __init__(self, argv):
        """
        main method
        @param argv: values of inline arguments
        """

        self.config = Configuration()

        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--verbose":
                self.config.set('verbose', True)

        self.config.setAgent('http://swaml.berlios.de/doap.rdf')
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), 'messages procesed'
Beispiel #12
0
class ConfigWizard(CommandLineUI):
    """
    SWAML's config wizard
    
    @author: Sergio Fdez
    @license: GPL
    """
    def requestData(self):
        """
        Queries the user a new configuration
        """

        self.config = Configuration()

        print 'Write your configuration options:'
        print '(default value goes between [...])'

        for var in self.config.config.keys():
            defaultValue = str(self.config.config[var])
            value = raw_input('\t - ' + var + '[' + defaultValue + ']: ')
            if (len(value) > 0):
                self.config.set(var, value)

    def printData(self):
        """
        Dump on hard disk the configuration
        """

        ini = ConfigParser.ConfigParser()

        ini.add_section(self.section)

        for var in self.config.config.keys():
            ini.set(self.section, var, str(self.config.config[var]))

        try:
            file = open(self.output, 'w+')
            ini.write(file)
            file.flush()
            file.close()
            print 'new config file created in', self.output, 'with chosen parameters'
        except IOError, detail:
            print 'Error exporting coordinates config file: ' + str(detail)
Beispiel #13
0
    def __init__(self, argv):
        """
        main method
        @param argv: values of inline arguments
        """

        self.config = Configuration()
        args_ret = self.args(argv, self.config)
        self.pub = Publisher(self.config)
        print str(self.pub.publish()), 'messages procesed'
 def requestData(self):
     """
     Queries the user a new configuration
     """
     
     self.config = Configuration()
     
     print 'Write your configuration options:'
     print '(default value goes between [...])'
     
     for var in self.config.config.keys():
         defaultValue = str(self.config.config[var])
         value = raw_input('\t - ' + var + '[' + defaultValue + ']: ')
         if (len(value) > 0):
             self.config.set(var, value)
Beispiel #15
0
    def __init__(self, argv):
        """
        main method
        @param argv: values of inline arguments
        """

        self.config = Configuration()

        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--verbose":
                self.config.set("verbose", True)

        self.config.setAgent(__agent__)
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), "messages procesed"
Beispiel #16
0
 def __init__(self, argv):
     """
     main method
     @param argv: values of inline arguments
     """
     
     self.config = Configuration()        
     
     for arg in argv:
         if arg == "-h" or arg == "--help":
             self.usage()
         elif arg == "-v" or arg == "--verbose":
             self.config.set('verbose', True)
             
     self.config.setAgent('http://swaml.berlios.de/doap.rdf')
     self.parseArgs(argv)
     self.list = MailingList(self.config)
     messages = self.list.publish()
     print str(messages), 'messages procesed'
Beispiel #17
0
class SWAML:
    """
    Main class of SWAML project
    
    @author: Sergio Fdez
    @license: GPL
    """

    def parseArgs(self, argv):
        """
        Getting params of default input
        
        @param argv: arguments values array
        """

        if not self.config.parse(argv):
            self.usage()

        # self.config.show()

    def usage(self):
        """
        Print help to use SWAML
        
        @todo: locate better name for format vars
        """

        print """
Usage: swaml.py configfile [options]
        
'swaml' transform the archives of a mailing list (in mbox format) into a semantic web friendly format (RDF in XML).

   'configfile'      : path to a configuration file compatible with RFC822.

Options:
   -v, --verbose     : turn on verbose mode.
   -V, --version     : show version.
   -h, --help        : print this help message and exit.

Report bugs to: <http://swaml.berlios.de/bugs>

"""
        sys.exit()

    def __init__(self, argv):
        """
        main method
        @param argv: values of inline arguments
        """

        self.config = Configuration()

        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--verbose":
                self.config.set("verbose", True)

        self.config.setAgent(__agent__)
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), "messages procesed"
Beispiel #18
0
import yaml

from pyasesm import ActiveLists

from classes.logger import Logger
from classes.configuration import Configuration
from classes.helper import Helper
from classes.misp import Misp
from classes.arcsight import ArcSight

LOGLEVEL='info'

if __name__ == '__main__':
    logger = Logger()
    logger.customize(LOGLEVEL)
    config = Configuration('Script synchronize MISP with ArcSight.')
    config.run_parser()
    #logger.customize(config.get('loglevel'))

    proxy = config.get('proxy')
    proxy = {'http': config.get('proxy'), 'https': config.get('proxy')}

    misp = Misp(config.get('misp-url'), config.get('misp-key'), not config.get('misp-no-verify-cert'))

    misp.loadRules(config.get('rules-file'))
    misp.downloadOrganisations()
    misp.loadPriorities(config.get('priorities-file'))

    if config.get('input'):
        misp.loadAttributes(config.get('input'))
    else:
Beispiel #19
0
def testConfiguration():
    print "\n****TEST CONFIGURATION****"
    rootDirectory = "./resources/test/configurations"
    files = Configuration.listConfigurationFiles(rootDirectory)
    selection = Configuration.userSelection(files)
    selectionFilepath = os.path.join(rootDirectory, files[selection])

    configuration = Configuration(selectionFilepath)
    #Template configuration
    useTemplate = configuration.getUseTemplate()
    templateName = configuration.getTemplateName()
    templateColor = configuration.getTemplateColor()
    #Printer configuration
    printerOsName = configuration.getPrinterOsName()
    printerOsFormat = configuration.getPrinterOsFormat()

    printerDpiStretch = configuration.getPrinterDpiStretch()
    printerMargin = configuration.getPrinterMargin()
    printerMarginDimension = configuration.getPrinterMarginDim()
    printerMarginTemplate = configuration.getPrinterMarginTemplate()
    printerMarginPhoto = configuration.getPrinterMarginPhoto()

    assert (len(files) > 0)

    #Test Printer configuration
    assert (printerOsName == "Canon_CP900")
    assert (printerOsFormat == "\"Postcard(4x6in)\"")

    #Test Format configuration
    assert (useTemplate)
    assert (
        templateName ==
        "./resources/test/template/COR-NOV16_elements-template-instagram_FLASH-gimp.jpg"
    )
    assert (templateColor == (216, 123, 98))

    assert (printerDpiStretch)
    assert (printerMargin == (-1, -1))
    assert (printerMarginDimension == "mm")
    assert (printerMarginTemplate == (30, 30))
    assert (printerMarginPhoto == (60, 60))
    print configuration
    print "TESTS ON CONFIGURATION PASSED SUCCESSFULLY"
Beispiel #20
0
class Battery_capacity_hill_decent():
    '''
    Associate each house with the nearest battery, then hill descent the violation of battery capacity.
    '''


    def __init__(self, district_id):
        if district_id == 1:
            self.district = district_1
        elif district_id == 2:
            self.district = district_2
        elif district_id == 3:
            self.district = district_3
        elif district_id == 4:
            self.district = district_4
        else:
            return False
        self.world = Configuration(district_id)
        self.batteries = self.district["batteries"]
        self.houses = self.district["houses"]
        self.costs = 0
        self.violation = 0


    def Update_violation(self):
        '''
        Update the violation of battery capacities.
        '''
        
        violation = 0
        self.costs = 0
        for battery in self.batteries:
            violation += max(0,(battery.energy_production - battery.capacity)) ** 2
            self.costs += battery.costs_battery
        self.violation = violation


    def reset_world(self):
        '''
        Empty all batteries.
        '''
        for battery in self.batteries:
            battery.empty_battery()
        self.costs = 0
    

    def distribute_houses(self):
        '''
        Associate each house with the nearest battery.
        '''
        
        for house in self.houses:
            mindist = float('inf')
            i=0
            while(i < len(self.batteries)):
                dist = abs(self.batteries[i].position_x - house.position_x) + abs(self.batteries[i].position_y - house.position_y)
                if dist < mindist:
                    mindist = dist
                    minindex = i
                i += 1
            self.batteries[minindex].add_house(house)
        self.Update_violation()
    

    def Relocate_random_house(self):
        '''
        Relocates a random house from one battery to another, then updates the battery violation.
        '''
        
        initial_violation = self.violation
        
        # Choose two different random batteries.
        b_1 = np.random.randint(0, len(self.batteries))
        while len(self.batteries[b_1].houses_in_battery) == 0:
            b_1 = np.random.randint(0, len(self.batteries))
        b_2 = np.random.randint(0, len(self.batteries))
        while b_2 == b_1:
            b_2 = np.random.randint(0, len(self.batteries))
            
        # Choose a random house in the first battery and relocate it to the second battery if this results in a lower violation of 
        # battery capacity.
        h_1 = np.random.randint(0, len(self.batteries[b_1].houses_in_battery))
        violation_dif_1 = max(0,(self.batteries[b_1].energy_production - self.batteries[b_1].capacity \
        - self.batteries[b_1].houses_in_battery[h_1].production)) ** 2 - max(0,(self.batteries[b_1].energy_production \
        - self.batteries[b_1].capacity)) ** 2
        violation_dif_2 = max(0,(self.batteries[b_2].energy_production - self.batteries[b_2].capacity + \
        self.batteries[b_1].houses_in_battery[h_1].production)) ** 2 - max(0,(self.batteries[b_2].energy_production - \
        self.batteries[b_2].capacity)) ** 2
        violation_dif = violation_dif_1 + violation_dif_2
        if violation_dif < 0:
            self.batteries[b_2].add_house(self.batteries[b_1].houses_in_battery[h_1])
            self.batteries[b_1].remove_house(self.batteries[b_1].houses_in_battery[h_1])
        self.Update_violation()
    

    def Find_valid_sol_1(self):
        '''
        Runs algorithm and return False if it gets stuck (if hill decent fails).
        '''
        
        same = 0
        while self.violation > 0 and same < 100:
            violation = self.violation
            self.Relocate_random_house()
            if violation == self.violation:
                same += 1
            else:
                same = 0
        if self.violation > 0:
            self.reset_world()
            return False
    

    def run(self):
        '''
        Repeats the algorithm untill it is not stuck.
        '''
        self.distribute_houses()
        while self.Find_valid_sol_1() == False:
            self.distribute_houses()
        return self.world.check50_neighbour_variant_own_costs()
Beispiel #21
0
class SWAML:
    """
    Main class of SWAML project
    
    @autor: Sergio Fdez
    @license: GPL
    """

    def parseArgs(self, argv):
        """
        Getting params of default input
        """

        try:
            opts, args = getopt.getopt(argv, "d:u:m:f:k:h", ["dir=","url=","mbox=","format=","kml=","help"])
        except getopt.GetoptError:
            self.usage()

        for opt, arg in opts:
            if opt in ("-h", "--help"):
                self.usage()
            elif opt in ("-d", "--dir") and arg:
                self.config.set("dir", arg)
            elif opt in ("-u", "--url") and arg:
                self.config.set("url", arg)
            elif opt in ("-m", "--mbox") and arg:
                self.config.set("mbox", arg)
            elif opt in ("-f", "--format") and arg:
                self.config.set("format", arg)
            elif opt in ("-k", "--kml") and arg:
                self.config.set("kml", arg)                                      
            else:
                self.usage()
                
        #self.config.show()


    def usage(self):
        """
        Print help to use SWAML
        
        @todo: locate better name for format vars
        """
        
        print """
Usage: swaml.py [OPTIONS]
        
'swaml' transform the archives of a mailing list (in mbox format) into a semantic web friendly format (RDF in XML).

Options:

   -d DIR, --dir=DIR            : use DIR to publish the RDF files; 'archive/' is used by default.

   -u URL, --url=URL            : base URL to browse archives.

   -m MBOX, --mbox=MBOX         : open MBOX file, 'mbox' by default value.

   -f FORMAT, --format=FORMAT   : path pattern to store the messages. FORMAT is an string that can contain following keys:

                                   	'DD': number of day that message was sent
                                   	'MM': number of month that message was sent
                                   	'MMM': short month string that message was sent
                                   	'MMMM': long month string that message was sent
                                   	'YYYY': year that message was sent
                                   	'ID': message numeric id

                                  The string 'YYYY-MMM/messageID.rdf' is used by default, but you can compose the string
                                  as you want (for example something like 'YYYY/MM/DD/ID.rdf').
   
   -k {yes/no}, --kml={yes/no]  : flag to activate export KML support.                                 

   -h, --help                   : print this help message and exit.

Report bugs to: <http://swaml.berlios.de/bugs>

"""
        sys.exit()
        

    def __init__(self, argv):
        """
        main method
        @param argv: values of inline arguments
        """
        
        self.config = Configuration()
        self.config.setAgent(__url__)
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), 'messages procesed'
Beispiel #22
0
class Random_house_sort():
    '''
    Random solution that doesn't violate battery capacities.
    '''
    
    
    def __init__(self, district_id):
        if district_id == 1:
            self.district = district_1
        elif district_id == 2:
            self.district = district_2
        elif district_id == 3:
            self.district = district_3
        elif district_id == 4:
            self.district = district_4
        else:
            return False
        self.batteries = []
        self.world = Configuration(district_id)
        lists = self.world.get_lists()
        for battery0 in lists[0]:
            self.batteries.append(battery0[2])
        self.houses = self.district["houses"]
        self.costs = 0
    

    def distribute_houses(self):
        '''
        Associate each house with a random battery.
        '''
        
        for house in self.houses:
            done = False
            negmaxcapacityleft = 0
            for battery in self.batteries:
                negcapleft = battery.energy_production - battery.capacity
                if negcapleft < negmaxcapacityleft:
                    negmaxcapacityleft = negcapleft
            maxcapleft = -negmaxcapacityleft
            if maxcapleft < house.production:
                return False
            while done == False:
                index = np.random.randint(0, len(self.batteries))
                if self.batteries[index].capacity - self.batteries[index].energy_production > house.production:
                    self.batteries[index].add_house(house)
                    done = True
        for battery in self.batteries:
            self.costs += battery.costs_battery
        return True
    

    def reset_world(self):
        '''
        Empties batteries (disassociates all houses from batteries).
        '''
        
        for battery in self.batteries:
            battery.empty_battery()
        self.costs = 0


    def run(self):
        '''
        Runs algorithm
        '''
        
        valid = False
        while valid == False:
            self.reset_world()
            valid = self.distribute_houses()
    
        return self.world.check50_neighbour_variant_own_costs()
Beispiel #23
0
class SWAML:
    """
    Main class of SWAML project
    
    @author: Sergio Fdez
    @license: GPL
    """
    def parseArgs(self, argv):
        """
        Getting params of default input
        
        @param argv: arguments values array
        """

        if not self.config.parse(argv):
            self.usage()

        #self.config.show()

    def usage(self):
        """
        Print help to use SWAML
        
        @todo: locate better name for format vars
        """

        print """
Usage: swaml.py configfile [options]
        
'swaml' transform the archives of a mailing list (in mbox format) into a semantic web friendly format (RDF in XML).

   'configfile'      : path to a configuration file compatible with RFC822.

Options:
   -v, --verbose     : turn on verbose mode.
   -V, --version     : show version.
   -h, --help        : print this help message and exit.

Report bugs to: <http://swaml.berlios.de/bugs>

"""
        sys.exit()

    def __init__(self, argv):
        """
        main method
        @param argv: values of inline arguments
        """

        self.config = Configuration()

        for arg in argv:
            if arg == "-h" or arg == "--help":
                self.usage()
            elif arg == "-v" or arg == "--verbose":
                self.config.set('verbose', True)

        self.config.setAgent('http://swaml.berlios.de/doap.rdf')
        self.parseArgs(argv)
        self.list = MailingList(self.config)
        messages = self.list.publish()
        print str(messages), 'messages procesed'
Beispiel #24
0
class optimum_deluxe():
    '''
    optimum_deluxe optimizes in 3 steps. 
    1: connect the house that is the cheapest to a battery, repeat untill all houses are connected. 
    2: relocate the house that results in the lowest cost per decreased battery violation, repeat untill convergence.
    3: switch the pair of houses that results in the lowest cost per decreased battery violation, repeat untill convergence.
    '''
    def __init__(self, district_id):
        self.world = Configuration(district_id)

    def connect_house(self, world, house, battery):
        '''
        connect house to battery the cheapest way
        '''

        # associate house with battery and initialize list of points connected to the battery.
        battery.add_house(house)
        battery_points = []
        lists = world.get_lists()

        # fill list of points connected to battery
        for battery0 in lists[0]:
            if battery0[2] == battery:
                battery_points.append([battery0[0], battery0[1]])
                for cable in battery0[3]:
                    battery_points.append(cable[0])
                    battery_points.append(cable[1])

        # get connected point nearest to house
        nearest_point = [-1, -1]
        dist = float('inf')
        house_point = [house.position_x, house.position_y]
        for point in battery_points:
            dist1 = abs(house_point[0] - point[0]) + abs(house_point[1] -
                                                         point[1])
            if dist1 < dist:
                dist = dist1
                nearest_point = point

        # make random path to nearest point
        x_orientation = 1
        y_orientation = 1
        if nearest_point[0] - house_point[0] < 0:
            x_orientation = -1
        if nearest_point[1] - house_point[1] < 0:
            y_orientation = -1
        x_dist = abs(nearest_point[0] - house_point[0])
        y_dist = abs(nearest_point[1] - house_point[1])
        current_point = house_point
        while x_dist + y_dist > 0:
            if np.random.randint(0, x_dist + y_dist) < x_dist:
                self.world.add_cable(
                    self.world.configuration[current_point[0]][
                        current_point[1]],
                    self.world.configuration[current_point[0] +
                                             x_orientation][current_point[1]],
                    battery)
                current_point = [
                    current_point[0] + x_orientation, current_point[1]
                ]
                x_dist -= 1
            else:
                self.world.add_cable(
                    self.world.configuration[current_point[0]][
                        current_point[1]],
                    self.world.configuration[current_point[0]][current_point[1]
                                                               +
                                                               y_orientation],
                    battery)
                current_point = [
                    current_point[0], current_point[1] + y_orientation
                ]
                y_dist -= 1

    def disconnect_house(self, world, house, battery):
        '''
        disassociates house from battery and remove excess cable.
        '''

        battery.remove_house(house)
        current_point = world.configuration[house.position_x][house.position_y]
        neighbours0 = self.neighbours_list(current_point, battery)
        neighbour_count = len(neighbours0)
        points_to_exclude = [[battery.position_x, battery.position_y]]
        for house1 in battery.houses_in_battery:
            points_to_exclude.append([house1.position_x, house1.position_y])

        while neighbour_count == 1 and [current_point.x, current_point.y
                                        ] not in points_to_exclude:
            next_point = neighbours0[0]
            world.delete_cable(current_point, neighbours0[0], battery)
            current_point = next_point
            neighbours0 = self.neighbours_list(current_point, battery)
            neighbour_count = len(neighbours0)

    def neighbours_list(self, point, battery):
        '''
        Returns neigbours in list format.
        '''

        neighbours = []
        if battery in point.neighbours:
            neighbours = point.neighbours[battery]
        return neighbours

    def check_costs_to_connect_house_to_battery(self, house, battery):
        '''
        Checks what it would cost to connect a house to a battery.
        '''

        costs = self.world.get_lists()[2]
        self.connect_house(self.world, house, battery)
        new_costs = self.world.get_lists()[2]
        self.disconnect_house(self.world, house, battery)
        return new_costs - costs

    def get_disconnected_houses_and_all_batteries(self, world):
        '''
        Returns lists of house that are not connected to a battery and all batteries.
        '''

        lists = world.get_lists()
        houses0 = lists[1]
        batteries0 = lists[0]
        houses = []
        batteries = []
        for house in houses0:
            houses.append(house[2])
        houses2 = []
        for battery1 in batteries0:
            battery = battery1[2]
            batteries.append(battery)
            houses_in_battery = battery.houses_in_battery
            for house2 in houses_in_battery:
                houses2.append(house2)
        houses3 = []
        for house4 in houses:
            if house4 not in houses2:
                houses3.append(house4)
        return houses3, batteries

    def connect_cheapest_house(self):
        '''
        Connect the house that is the cheapest to connect.
        '''

        houses, batteries = self.get_disconnected_houses_and_all_batteries(
            self.world)
        if len(houses) == 0:
            return False
        else:
            house0 = None
            battery0 = None
            cost = float('inf')
            for house in houses:
                for battery in batteries:
                    cost1 = self.check_costs_to_connect_house_to_battery(
                        house, battery)
                    if cost1 < cost:
                        house0 = house
                        battery0 = battery
                        cost = cost1
            self.connect_house(self.world, house0, battery0)
            print(self.world.get_lists()[2])
            print(self.world.check('Optimum Deluxe'))
            print(self.world.text_grid())
            return True

    def connect_all_houses(self):
        '''
        Connect the cheapest house untill all houses are connected.
        '''

        while self.connect_cheapest_house():
            pass

    def check_costs_to_relocate_house(self, house, battery_1, battery_2):
        '''
        Check what it would cost to relocate a battery to another battery and what the decrease of the battery capacity violation would be.
        '''

        old_costs = self.world.get_lists()[2]
        old_bat_violation = self.world.check('Optimum Deluxe')[4]
        self.disconnect_house(self.world, house, battery_1)
        self.connect_house(self.world, house, battery_2)
        new_costs = self.world.get_lists()[2]
        new_bat_violation = self.world.check('Optimum Deluxe')[4]
        bat_gained = old_bat_violation - new_bat_violation
        extra_costs = new_costs - old_costs
        self.disconnect_house(self.world, house, battery_2)
        self.connect_house(self.world, house, battery_1)
        return bat_gained, extra_costs

    def do_best_relocation_of_house(self):
        '''
        Relocate the house that results in the lowest cost per decreased battery violation.
        '''

        # initialize lists and variables.
        houses, batteries = self.get_disconnected_houses_and_all_batteries(
            self.world)
        battery0_1 = None
        battery0_2 = None
        house0 = None
        min_cost_per_bat_gained = float('inf')

        # find smallest cost per battery violation descent.
        for i in range(len(batteries)):
            for house in batteries[i].houses_in_battery:
                for j in range(len(batteries)):
                    if (j != i):
                        bat_gained, extra_costs = self.check_costs_to_relocate_house(
                            house, batteries[i], batteries[j])
                        if bat_gained > 0:
                            cost_per_bat_gained = extra_costs / bat_gained
                            if cost_per_bat_gained < min_cost_per_bat_gained:
                                battery0_1 = batteries[i]
                                battery0_2 = batteries[j]
                                house0 = house
                                min_cost_per_bat_gained = cost_per_bat_gained

        # perform the relocation if the battery violation descent is greater than zero, otherwise return False.
        if battery0_1 == None:
            return False
        else:
            self.disconnect_house(self.world, house0, battery0_1)
            self.connect_house(self.world, house0, battery0_2)
            print(self.world.get_lists()[2])
            print(self.world.check('Optimum Deluxe'))
            print(self.world.text_grid())
            return True

    def relocate_untill_convergence(self):
        '''
        Relocate houses untill convergence.
        '''

        while self.do_best_relocation_of_house():
            pass

    def switch_houses(self, world, battery_1, house_1, battery_2, house_2):
        '''
        Switches houses (between two batteries).
        '''

        self.disconnect_house(world, house_1, battery_1)
        self.disconnect_house(world, house_2, battery_2)
        self.connect_house(world, house_1, battery_2)
        self.connect_house(world, house_2, battery_1)

    def check_costs_to_switch_houses(self, battery_1, house_1, battery_2,
                                     house_2):
        '''
        Checks what it would cost to switch two houses between batteries.
        '''

        old_costs = self.world.get_lists()[2]
        old_bat_violation = self.world.check('Optimum Deluxe')[4]
        self.switch_houses(self.world, battery_1, house_1, battery_2, house_2)
        new_costs = self.world.get_lists()[2]
        new_bat_violation = self.world.check('Optimum Deluxe')[4]
        bat_gained = old_bat_violation - new_bat_violation
        extra_costs = new_costs - old_costs
        self.switch_houses(self.world, battery_2, house_1, battery_1, house_2)
        return bat_gained, extra_costs

    def do_best_switch_of_houses(self):
        '''
        Perform the switch of houses that results in the lowest cost per decreased battery violation.
        '''

        # initialize lists and variables.
        houses, batteries = self.get_disconnected_houses_and_all_batteries(
            self.world)
        battery0_1 = None
        battery0_2 = None
        house0_1 = None
        house0_2 = None
        min_cost_per_bat_gained = float('inf')

        # find smallest cost per battery violation descent.
        for i in range(len(batteries)):
            houses_3 = copy.copy(batteries[i].houses_in_battery)
            for house_1 in houses_3:
                for j in range(len(batteries)):
                    if (j != i):
                        houses_4 = copy.copy(batteries[j].houses_in_battery)
                        for house_2 in houses_4:
                            bat_gained, extra_costs = self.check_costs_to_switch_houses(
                                batteries[i], house_1, batteries[j], house_2)
                            if bat_gained > 0:
                                cost_per_bat_gained = extra_costs / bat_gained
                                if cost_per_bat_gained < min_cost_per_bat_gained:
                                    battery0_1 = batteries[i]
                                    battery0_2 = batteries[j]
                                    house0_1 = house_1
                                    house0_2 = house_2
                                    min_cost_per_bat_gained = cost_per_bat_gained

        # perform the relocation if the battery violation descent is greater than zero, otherwise return False.
        if battery0_1 == None:
            return False
        else:
            self.switch_houses(self.world, battery0_1, house0_1, battery0_2,
                               house0_2)
            print(self.world.get_lists()[2])
            print(self.world.check('Optimum Deluxe'))
            print(self.world.text_grid())
            return True

    def switch_houses_until_convergence(self):
        '''
        Switch houses untill battery violation is zero.
        '''

        while self.do_best_switch_of_houses():
            pass

    def run(self):
        '''
        Runs algorithm and returns result in check50 format.
        '''

        self.connect_all_houses()
        self.relocate_untill_convergence()
        self.switch_houses_until_convergence()
        return self.world.check50_neighbour_variant()
Beispiel #25
0
def main():

    #The root directory
    inputDir = "/Users/manu/Desktop/wistiti/"
    #The configuration file directory
    configDir = os.path.join(inputDir, "configurations")

    #USE CONFIGURATION FILE
    #Ask user for configuration
    files = Configuration.listConfigurationFiles(configDir)
    selection = Configuration.userSelection(files)
    selectionFilepath = os.path.join(configDir, files[selection])
    cfg = Configuration(selectionFilepath)

    print cfg

    #templateFile = "./resources/test/template/COR-MARS16_elements-template-gimp.jpg"
    useTemplate = cfg.getUseTemplate()
    if (useTemplate == True):
        templateFile = cfg.getTemplateName()
    else:
        templateFile = "NoTemplate"

    #marginColor = (84,158,167)
    marginColor = cfg.getTemplateColor()
    #TODO = Manage difference between width and height margins
    templateMargin = cfg.getPrinterMarginTemplate()[0]
    photoMargin = cfg.getPrinterMarginPhoto()[0]
    #The printer
    if (cfg.getPrinterOsName() == "Canon_CP900"):
        printFormat = PrintFormat.SelphyCP900(
            dpiStretch=cfg.getPrinterDpiStretch())
    elif (cfg.getPrinterOsName() == "Dai_Nippon_Printing_DP_DS620"):
        printFormat = PrintFormat.DNPDS620(
            dpiStretch=cfg.getPrinterDpiStretch())
    elif (cfg.getPrinterOsName() == "DNPDS620"):
        print "No osname and osformat for this printer %s\n"\
              "Change the configuration file. Quit" %(cfg.getPrinterOsName())
        return
    else:
        print "No printer with this name %s, quit" % (cfg.getPrinterOsName())
        return
    printFormat.setPrinterMargin(cfg.getPrinterMargin()[0],
                                 cfg.getPrinterMargin()[1],
                                 cfg.getPrinterMarginDim)
    print printFormat
    #END OF USE CONFIGURATION FILE

    #Add a margin on the template (add new pixel for printer margin)
    templateFile = addMarginOnTemplate(templateFile,
                                       templateMargin,
                                       marginColor=marginColor)

    #Get the subdirectories that include instagram pictures
    subDirArray = getImmediateSubdirectories(inputDir)

    #User chooses the subdirectory
    userIndexSelection = userSelectionInArray(subDirArray)
    inputDir = os.path.join(inputDir, subDirArray[userIndexSelection])
    #Get the images list (jpg)
    files = listScreenShotFiles(inputDir)

    #Display information for user
    print "********************************"
    print "%s files found" % (len(files))
    print files
    print "********************************"

    userInput = ""
    index = 0
    if (len(files) == 0):
        print "No compatible file in this directory, quit..."
        return

    while (userInput != "q"):
        #Open the picture image
        filepath = os.path.join(inputDir, files[index])
        (filepathWithoutExtension, extension) = os.path.splitext(filepath)

        #fileOutput = filepathWithoutExtension + "-python" + extension
        #print filepathWithoutExtension
        #print extension
        #print fileOutput

        #Add a photo on the template
        photoPath = addPhotoOnTemplate(filepath,
                                       templateFile,
                                       margin=photoMargin)
        im = Image.open(photoPath)

        #exif_data = im._getexif()
        #print im.info
        #print exif_data
        photo = Photo(im.size[0], im.size[1])
        photo.computePpmm(printFormat)
        print "********************************"
        print "File %s on %s : %s" % (index + 1, len(files), files[index])
        print photo
        fileOutput = generateFilepathWithSuffix(photoPath, "-CP900-print")
        im.save(fileOutput, 'jpeg', dpi=(photo.ppiX, photo.ppiY))
        im2 = Image.open(fileOutput)

        #User choose the action
        userInput = raw_input("Print? print/next/display/quit [p/n/d/q]")
        #print "Resultat %s" % userInput
        if userInput == "p":
            print im2.info
            printCommand = Printer.computePrinterCommand(
                fileOutput, cfg.getPrinterOsName(), cfg.getPrinterOsFormat())
            Printer.sendPrinterJob(printCommand)
            print "INFO : YOU CAN PRINT THE SAME IMAGE"
        elif userInput == "n":
            print "Next picture"
            index += 1
        elif userInput == "d":
            print "Display"
            im.show()
        elif userInput == "q":
            print "Quit"
        else:
            print "Unknown command"

        if (index >= len(files)):
            userInput = "q"
            print "No more picture, quit..."
Beispiel #26
0
 def __init__(self, district_numb):
     # loads the batteries and houses into district variable of type configuration
     self.the_district = Configuration(district_numb)
     self.the_district.create_district()
Beispiel #27
0
 def __init__(self, district_id):
     self.world = Configuration(district_id)
Beispiel #28
0
class Combining_algorithms():
    '''
    The Combining_algorithms class brings the two types of algorithms that the
    Optimum Prime program uses to solve this problem together: the algorithms
    that devide the houses amoungst the batteries in the configuration and the
    algorithms that lay the cables that connect these houses with the cables.
    The initialisation is done using the number of district instance the user
    wants to use.
    '''
    def __init__(self, district_numb):
        # loads the batteries and houses into district variable of type configuration
        self.the_district = Configuration(district_numb)
        self.the_district.create_district()

    # Greedy_house allocation & Astar cable drawing - assumption 1 cable 1 house
    def greedy_house_manhatten_cable(self, cable_sharing):
        '''
        Uses a greedy algorithm with a huristic based on proximity of a house to
        a battery to devide the houses amoungst the batteries. Than uses the manhatten
        distance to lay cables between thouse houses and their batteries. Finally, prints
        the total costs of the solution.
        '''

        self.greedy_house_devide = Greedy(self.the_district)
        self.greedy_house_devide.proximity_sort()
        self.astar_cable = Cable(self.the_district)
        self.astar_cable.cable_list_batteries(self.the_district.all_batteries,
                                              cable_sharing)
        self.the_district.refresh_config()
        return self.greedy_house_devide.district.cs50_check(cable_sharing)

    def annealing_hill_climber(self, step_num, cable_sharing):
        '''
        This method first applies the simulating annealing algorithm to sort all the houses
        in the batteries. Then it applies the hill climber algorithm to modify this solution
        to an even better one. It takes step_num steps in the hill climber algorithm.
        '''

        self.annealing_house_devide1 = simulated_annealing(self.the_district)
        self.annealing_house_devide1.creating_starting_possition()
        self.annealing_house_devide1.running_simulated_annealing(cable_sharing)

        self.astar_cable2 = Cable(self.the_district)
        self.astar_cable2.cable_list_batteries(self.the_district.all_batteries,
                                               False)

        self.hill = Hill_climber(self.the_district)
        self.hill.climb_the_hill(step_num)
        self.the_district.refresh_config()
        return self.annealing_house_devide1.district.cs50_check(cable_sharing)

    def greedy_then_hill_climber(self, step_num, cable_sharing):
        self.greedy_house_manhatten_cable(cable_sharing)

        hill_climber = Hill_climber(self.the_district)

        hill_climber.climb_the_hill(step_num)

        return self.the_district.cs50_check(cable_sharing)

    # simulated anealing house distribution & Astar cable drawing - assumption 1 cable 1 house
    def simulated_annealing_house_manhatten_cable(self, cable_sharing):
        '''
        Combines a simulated annealing algorithm with a huristic based on proximity of a house to a
        battery and the fullness of a battery compared to other batteries to devide the houses amoung
        the batteries. Than uses the manhatten distance to lay cables between thouse houses and their
        batteries. Finally, prints the total costs of the solution.
        '''

        self.sa_distribution = simulated_annealing(self.the_district)
        self.sa_distribution.creating_starting_possition()
        self.sa_distribution.running_simulated_annealing(cable_sharing)
        self.astar_cable2 = Cable(self.the_district)
        self.astar_cable2.cable_list_batteries(self.the_district.all_batteries,
                                               cable_sharing)
        self.the_district.refresh_config()
        return self.sa_distribution.district.cs50_check(cable_sharing)

    def random_greedy_astar_manhatten_cable(self, rounds, cable_sharing):
        '''
        Introduces some randomness too a greedy algorithm with a huristic based on proximity of a house
        to a battery. Than uses the manhatten distance to lay cables between thouse houses and their
        batteries. Finally, prints the total costs of the solution.
        '''

        self.random_greedy = Greedy(self.the_district)
        self.random_greedy.random_greedy(rounds)
        self.astar_cable2 = Cable(self.the_district)
        self.astar_cable2.cable_list_batteries(self.the_district.all_batteries,
                                               cable_sharing)
        self.the_district.refresh_config()
        return self.random_greedy.district.cs50_check(cable_sharing)
Beispiel #29
0
def run(options, algorithm, statistics_values):
    #we need a fixed seed to keep the experiments reproducible
    #we choose the total number of passenger vehicles (osm.passenger.trips.xml file)
    logger.info('algorithm: ' + str(options.algorithm))

    ev = statistics_values.ev

    logger.info('Chosen EV ' + str(ev))

    ev_entered_in_simulation = False
    conf = Configuration(ev, options.scenario_folder)

    if options.prefix == 'staticdynamic':
        conf.set_staticdynamic()

    logger.info('tls order')
    logger.info([
        conf.edges[edge]['tl']['name'] for edge in conf.edges_order
        if edge in conf.edges_with_tl
    ])

    algorithm.setup(conf, statistics_values, ev)

    algorithm.configure()

    # return
    while traci.simulation.getMinExpectedNumber() > 0:
        step = int(traci.simulation.getTime())
        statistics_values.update_cars_by_time(step, traci.vehicle.getIDCount())

        algorithm.execute_before_step_simulation(step)

        logger.info('step ' + str(step))
        traci.simulationStep()

        if not ev_entered_in_simulation:
            ev_entered_in_simulation, when_entered = track_vehicle(
                ev, options, step)

        if ev_entered_in_simulation and statistics_values.n_when_ev_enter < 0:
            algorithm.conf.update_values()
            statistics_values.n_when_ev_enter = traci.vehicle.getIDCount() - 1
            statistics_values.update_vehicles_affected_by_ev_dispatch()

        algorithm.execute_step(step, ev_entered_in_simulation)

        if ev in traci.vehicle.getIDList():
            statistics_values.update_vehicles_affected_by_ev()
            statistics_values.distance_travelled = traci.vehicle.getDistance(
                ev)
            statistics_values.update_vehicles_on_tl()
            logger.info('ev ' + str(ev) + ' has travelled ' +
                        str(statistics_values.distance_travelled) + 'm')

        if ev in traci.simulation.getStartingTeleportIDList():
            statistics_values.was_teleported = True

        if statistics_values.ev_end == -1 and (
                traci.vehicle.getIDCount() <= 0 or
            (ev_entered_in_simulation
             and ev not in traci.vehicle.getIDList())):
            if ev_entered_in_simulation and ev not in traci.vehicle.getIDList(
            ):
                statistics_values.ev_end = step
                statistics_values.n_when_ev_left = traci.vehicle.getIDCount(
                ) - 1
                statistics_values.ev_start = when_entered
                algorithm.finish()

            if statistics_values.was_teleported:
                logger.info(str(ev) + ' has been teleported!')

        statistics_values.n_of_teleporteds |= set(
            traci.simulation.getStartingTeleportIDList())

    statistics_values.crossed_tls_by_ev = len(algorithm.conf._edges_with_tl)

    statistics_values.print_summary(ev)

    traci.close()
    sys.stdout.flush()

    logger.info('finished!')
    logger.info('ev(' + str(ev) + ') started ' +
                str(statistics_values.ev_start) + ' and ended ' +
                str(statistics_values.ev_end))

    statistics_values.get_results(ev, step)

    statistics_values.generate_json(options.skip, algorithm.instance_name())