class SubgraphGenerator(common.Script): '''Generates 2 graphs for subgraph isomorphism or maximum common induced subgraph problem.''' parameters = [ common.Parameter('number_of_vertices1'), common.Parameter('edge_probability1'), common.Parameter('number_of_vertices2'), common.Parameter('edge_probability2') ] def __init__(self): # Instance variables are initialized so that subclasses could use them self.first_command_line_argument = 2 self.check_command_line_arguments() self.arguments = [(int(sys.argv[i - 1]), float(sys.argv[i])) for i in range(3, len(sys.argv), 2)] self.generate_and_write_to_file() def generate_and_write_to_file(self): self.matrices = [ common.initialize_matrix(self.arguments[i][0]) for i in range(len(self.arguments)) ] for i in range(len(self.arguments)): for j in range(self.arguments[i][0]): for k in range(j): if random.random() < self.arguments[i][1]: self.matrices[i][j][k] = self.matrices[i][k][j] = 1 with open(SUBGRAPH_FILENAME, 'w') as f: for i in range(len(self.arguments)): f.write('n{} = {};\n'.format(i + 1, self.arguments[i][0])) f.write( dzn_formatting.matrix(self.matrices[i], 'adjacent' + str(i + 1)))
class CliqueGenerator(common.Script): '''Generates graphs for max clique optimization & decision problems.''' parameters = [ common.Parameter('number_of_vertices'), common.Parameter('edge_probability', float), common.Parameter('size_of_clique', int, False) ] def __init__(self): super().__init__() unsorted_matrix = common.initialize_matrix( self.arguments['number_of_vertices']) # fill the matrix for i in range(self.arguments['number_of_vertices']): for j in range(i): if random.random() < self.arguments['edge_probability']: unsorted_matrix[i][j] = unsorted_matrix[j][i] = 1 # sort the matrix indices = sorted(range(self.arguments['number_of_vertices']), key=lambda x: sum(unsorted_matrix[x]), reverse=True) matrix = common.initialize_matrix(self.arguments['number_of_vertices']) for i, old_i in enumerate(indices): for j, old_j in enumerate(indices): matrix[i][j] = unsorted_matrix[old_i][old_j] # output the matrix with open(CLIQUE_FILENAME, 'w') as f: f.write('n = {};\n'.format(self.arguments['number_of_vertices'])) if 'size_of_clique' in self.arguments: f.write('k = {};\n'.format(self.arguments['size_of_clique'])) f.write(dzn_formatting.matrix(matrix))
class LabelledSubgraphCliqueEncoding(SubgraphGenerator): '''Uses SubgraphGenerator to generate 2 labelled graphs for a maximum common induced subgraph problem and then encodes them as max clique. Label_probability is the probability of assigning a random label in [1, vertices1 + vertices2]. Otherwise a 0 is assigned.''' parameters = list( itertools.chain.from_iterable( (common.Parameter('vertices' + str(i)), common.Parameter('edge_probability' + str(i)), common.Parameter('label_probability' + str(i))) for i in range(1, 3))) def __init__(self): # parse the command line arguments self.first_command_line_argument = 2 self.check_command_line_arguments() self.arguments = [(int(sys.argv[i - 2]), float(sys.argv[i - 1]), float(sys.argv[i])) for i in range(4, len(sys.argv), 3)] # call the superclass to generate the 2 graphs self.generate_and_write_to_file() n1 = self.arguments[0][0] n2 = self.arguments[1][0] # generate the labels labels = [ ] # labels[i] is a list of labels for all vertices of graph i for n, _, l in self.arguments: labels.append([ random.randint(1, n1 + n2) if random.random() < l else 0 for j in range(n) ]) # write then to the file already generated by SubgraphGenerator with open(SUBGRAPH_FILENAME, 'a') as f: for i in range(len(self.arguments)): f.write('vLabel{} = [{}];\n'.format( i + 1, ', '.join(map(str, labels[i])))) # assign a new 'name' for all pairs of vertices that can be matched encoding = {} n = 0 for v1 in range(n1): for v2 in range(n2): if labels[0][v1] == labels[1][v2]: encoding[(v1, v2)] = n n += 1 # generate an adjacency matrix for the clique problem clique = common.initialize_matrix(n) for (a, b), (c, d) in itertools.product(encoding, repeat=2): if a != c and b != d and self.matrices[0][a][c] == self.matrices[ 1][b][d]: clique[encoding[(a, b)]][encoding[(c, d)]] = 1 # write it to file with open(CLIQUE_FILENAME, 'w') as f: f.write('n = {};\n'.format(n)) f.write(dzn_formatting.matrix(clique))
def main(): try: client = login() except common.LoginError as e: print e sys.exit(1) commands = common.Command.index( common.Command("log", log, common.Parameter.logging_level(required=False, help="Logging level"), help="Set logging level"), common.Command("internal", internal, help="Get current internal room ID"), common.Command("id", get_id, common.Parameter.penguin_name(required=False, help="Penguin name"), varargs=common.VarArgs.SINGLE_THREADED, help="Get penguin ID"), common.Command("name", name, common.Parameter.int_param("penguin_id", required=False, help="Penguin ID"), varargs=common.VarArgs.SINGLE_THREADED, help="Get penguin name"), common.Command("room", room, common.Parameter("room_name", common.get_json("rooms").values(), required=False, help="Room name"), help="Go to room"), common.Command("igloo", igloo, common.Parameter.penguin_name(required=False, help="Penguin name"), help="Go to igloo"), common.Command("penguins", penguins, help="Get all penguins in current room"), common.Command("color", color, common.Parameter.int_param("item_id", required=False, help="Color item ID"), help="Get current color item ID / Equip color item"), common.Command("head", head, common.Parameter.int_param("item_id", required=False, help="Head item ID"), help="Get current head item ID / Equip head item"), common.Command("face", face, common.Parameter.int_param("item_id", required=False, help="Face item ID"), help="Get current face item ID / Equip face item"), common.Command("neck", neck, common.Parameter.int_param("item_id", required=False, help="Neck item ID"), help="Get current neck item ID / Equip neck item"), common.Command("body", body, common.Parameter.int_param("item_id", required=False, help="Body item ID"), help="Get current body item ID / Equip body item"), common.Command("hand", hand, common.Parameter.int_param("item_id", required=False, help="Hand item ID"), help="Get current hand item ID / Equip hand item"), common.Command("feet", feet, common.Parameter.int_param("item_id", required=False, help="Feet item ID"), help="Get current feet item ID / Equip feet item"), common.Command("pin", pin, common.Parameter.int_param("item_id", required=False, help="Pin item ID"), help="Get current pin item ID / Equip pin item"), common.Command( "background", background, common.Parameter.int_param("item_id", required=False, help="Background item ID"), help="Get current background item ID / Equip background item"), common.Command("clothes", clothes, common.Parameter.penguin_name(required=False, help="Penguin name"), varargs=common.VarArgs.SINGLE_THREADED, help="Get all currently equipped item IDs"), common.Command("inventory", inventory, help="Get current inventory"), common.Command("buddies", buddies, help="Get all current buddies"), common.Command("stamps", stamps, common.Parameter.penguin_name(required=False, help="Penguin name"), help="Get all currently earned stamps"), common.Command("walk", Client.walk, common.Parameter.int_param("x", help="X"), common.Parameter.int_param("y", help="Y"), help="Walk"), common.Command("dance", Client.dance, help="Dance"), common.Command("wave", Client.wave, help="Wave"), common.Command( "sit", Client.sit, common.Parameter("direction", ["s", "e", "w", "nw", "sw", "ne", "se", "n"], required=False, help="Direction"), help="Sit"), common.Command("snowball", Client.snowball, common.Parameter.int_param("x", help="X"), common.Parameter.int_param("y", help="Y"), help="Throw snowball"), common.Command("say", say, varargs=common.VarArgs.NORMAL, help="Say message"), common.Command("joke", Client.joke, common.Parameter.int_param("joke_id", help="Joke ID"), help="Tell a joke"), common.Command("emote", Client.emote, common.Parameter.int_param("emote_id", help="Emote ID"), help="React an emote"), common.Command( "mail", mail, common.Parameter.other_penguin_name(help="Penguin name"), common.Parameter.int_param("postcard_id", help="Postcard ID"), help="Send a postcard"), common.Command("buy", Client.add_item, common.Parameter.int_param("item_id", help="Item ID"), varargs=common.VarArgs.MULTI_THREADED, help="Buy item"), common.Command("ai", Client.add_item, common.Parameter.int_param("item_id", help="Item ID"), varargs=common.VarArgs.MULTI_THREADED, help="Buy item"), common.Command("coins", coins, common.Parameter.int_param("amount", required=False, help="Amount"), help="Get current coins / Earn coins"), common.Command("ac", Client.add_coins, common.Parameter.int_param("amount", help="Amount"), help="Earn coins"), common.Command("stamp", Client.add_stamp, common.Parameter.int_param("stamp_id", help="Stamp ID"), varargs=common.VarArgs.MULTI_THREADED, help="Earn stamp"), common.Command("add_igloo", Client.add_igloo, common.Parameter.int_param("igloo_id", help="Igloo ID"), varargs=common.VarArgs.MULTI_THREADED, help="Buy igloo"), common.Command("add_furniture", Client.add_furniture, common.Parameter.int_param("furniture_id", help="Furniture ID"), varargs=common.VarArgs.MULTI_THREADED, help="Buy furniture"), common.Command("music", Client.igloo_music, common.Parameter.int_param("music_id", help="Music ID"), help="Set current igloo music"), common.Command( "buddy", buddy, common.Parameter.other_penguin_name(help="Penguin name"), varargs=common.VarArgs.MULTI_THREADED, help="Send buddy request"), common.Command( "find", find, common.Parameter.other_penguin_name(help="Penguin name"), varargs=common.VarArgs.MULTI_THREADED, help="Find buddy"), common.Command( "follow", follow, common.Parameter.other_penguin_name(help="Penguin name"), help="Follow penguin"), common.Command("unfollow", Client.unfollow, help="Stop following"), common.Command("logout", logout, help="Logout"), common.Command("exit", logout, help="Logout"), common.Command("quit", logout, help="Logout")) while client.connected: try: command, params = common.Command.read(client, commands) except EOFError: logout(client) break command.execute(client, params)
class Scheduler(common.Script): parameters = [ common.Parameter('model', str), common.Parameter('output_format', str), common.Parameter('file1', str), common.Parameter('file2', str) ] def __init__(self): super().__init__( 1, """ Supported models: cp, vertex-weights, vertex-edge-weights. Supported output formats: dzn (for all models), dimacs (for vertex-weights). To round all numbers to integers, add 'int' as an extra argument. To use a different file extension, provide it as an extra argument.""") # initialize the graphs formats = { 'CMU': representations.Cmu, 'GREC': representations.Grec, 'Mutagenicity': representations.Muta, 'Protein': representations.Protein } for f in formats: if f in self.arguments['file1']: if f not in self.arguments['file2']: raise ValueError( 'The two files should be from the same dataset') int_version = 'int' in self.optional_parameters() g1 = formats[f](self.arguments['file1'], int_version) g2 = formats[f](self.arguments['file2'], int_version) filename = self.new_filename(f) break if 'g1' not in locals(): raise RuntimeError( "I can't figure out which dataset the files are from") # create the models encodings = { 'cp': models.ConstraintProgramming, 'vertex-weights': models.VertexWeights, 'vertex-edge-weights': models.VertexEdgeWeights } if self.arguments['model'] not in encodings: raise ValueError('Incorrect model') model = encodings[self.arguments['model']](g1, g2, filename) if self.arguments['output_format'] == 'dzn': model.write_dzn(filename) elif self.arguments['output_format'] == 'dimacs': model.write_dimacs(filename) else: raise ValueError('Incorrect output format') def optional_parameters(self): return sys.argv[len(self.parameters) + 1:] def new_filename(self, dataset): extension = 'dzn' if self.arguments['output_format'] == 'dzn' else 'txt' for arg in self.optional_parameters(): if arg != 'int': extension = arg.strip() break return os.path.join( 'graphs', self.arguments['output_format'], self.arguments['model'], dataset, '-'.join([ os.path.basename(f[:f.rfind('.')]) for f in [self.arguments['file1'], self.arguments['file2']] ]) + '.' + extension)