prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models from django.contrib.auth.models import User import MySQLdb # Create your models here. class Comentario(models.Model): """Comentario""" contenido = models.TextField(help_text='Escribe un comentario') fecha_coment = models.DateField(auto_now=True) def __unicode__(self): return self.contenido class Estado(models.Model): """Estado""" nom_estado = models.CharField(max_length=50) def __unicode__(self): return nom_estado class Categoria(models.Model): """Categoria""" nombre = models.CharField(max_length=50) descripcion = models.TextField(help_text='Escribe una descripcion de la categoria') class Entrada(models.Model): """Entrada""" autor = models.ForeignKey(User) comentario = models.ForeignKey(Comentario) estado = models.ForeignKey(Estado) titulo = models.CharField(max_length=100) contenido = models.TextField(help_text='Redacta el contenido') fecha_pub = models.DateField(auto_now=True) def <|fim_middle|>(self): return self.titulo class Agregador(models.Model): """agreador""" entrada = models.ForeignKey(Entrada) categoria = models.ManyToManyField(Categoria)<|fim▁end|>
__unicode__
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \<|fim▁hole|> else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind)<|fim▁end|>
self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): <|fim_middle|> <|fim▁end|>
""" PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): <|fim_middle|> def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
""" :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect()
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): <|fim_middle|> def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): <|fim_middle|> def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
""" Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): <|fim_middle|> def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1])
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): <|fim_middle|> def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): <|fim_middle|> def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind])
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): <|fim_middle|> def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): <|fim_middle|> def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
self.cake_view_widget.phases[ind].add_line()
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): <|fim_middle|> <|fim▁end|>
self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: <|fim_middle|> else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
cake_tth = self.model.calibration_model.tth
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: <|fim_middle|> reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
cake_tth = self.model.cake_tth
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: <|fim_middle|> elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind])
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: <|fim_middle|> return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind])
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): <|fim_middle|> else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
self.cake_view_widget.show_cake_phase(ind)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: <|fim_middle|> def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
self.cake_view_widget.hide_cake_phase(ind)
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def <|fim_middle|>(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
__init__
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def <|fim_middle|>(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
connect
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def <|fim_middle|>(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
get_phase_position_and_intensities
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def <|fim_middle|>(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
add_phase_plot
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def <|fim_middle|>(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
update_phase_lines
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def <|fim_middle|>(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
update_phase_color
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def <|fim_middle|>(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
update_phase_visible
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def <|fim_middle|>(self, ind): self.cake_view_widget.phases[ind].add_line() def reflection_deleted(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
reflection_added
<|file_name|>PhaseInCakeController.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany # Copyright (C) 2019-2020 DESY, Hamburg, Germany # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from ....model.util.HelperModule import get_partial_index # imports for type hinting in PyCharm -- DO NOT DELETE from ....model.DioptasModel import DioptasModel from ....widgets.integration import IntegrationWidget from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget class PhaseInCakeController(object): """ PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view. """ def __init__(self, integration_widget, dioptas_model): """ :param integration_widget: Reference to an IntegrationWidget :param dioptas_model: reference to DioptasModel object :type integration_widget: IntegrationWidget :type dioptas_model: DioptasModel """ self.model = dioptas_model self.phase_model = self.model.phase_model self.integration_widget = integration_widget self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget self.connect() def connect(self): self.phase_model.phase_added.connect(self.add_phase_plot) self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase) self.phase_model.phase_changed.connect(self.update_phase_lines) self.phase_model.phase_changed.connect(self.update_phase_color) self.phase_model.phase_changed.connect(self.update_phase_visible) self.phase_model.reflection_added.connect(self.reflection_added) self.phase_model.reflection_deleted.connect(self.reflection_deleted) def get_phase_position_and_intensities(self, ind, clip=True): """ Obtains the positions and intensities for lines of a phase with an index ind within the cake view. No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in the ImgWidget based on the length of the clipped and not clipped lists. :param ind: the index of the phase :param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger than the :return: line_positions, line_intensities """ if self.model.cake_tth is None: cake_tth = self.model.calibration_model.tth else: cake_tth = self.model.cake_tth reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth', self.model.calibration_model.wavelength * 1e10) reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]] cake_line_positions = [] cake_line_intensities = [] for ind, tth in enumerate(reflections_tth): pos_ind = get_partial_index(cake_tth, tth) if pos_ind is not None: cake_line_positions.append(pos_ind + 0.5) cake_line_intensities.append(reflections_intensities[ind]) elif clip is False: cake_line_positions.append(0) cake_line_intensities.append(reflections_intensities[ind]) return cake_line_positions, cake_line_intensities def add_phase_plot(self): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False) self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities, self.phase_model.phase_colors[-1]) def update_phase_lines(self, ind): cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind) self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities) def update_phase_color(self, ind): self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind]) def update_phase_visible(self, ind): if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \ self.integration_widget.img_phases_btn.isChecked(): self.cake_view_widget.show_cake_phase(ind) else: self.cake_view_widget.hide_cake_phase(ind) def reflection_added(self, ind): self.cake_view_widget.phases[ind].add_line() def <|fim_middle|>(self, phase_ind, reflection_ind): self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind) <|fim▁end|>
reflection_deleted
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState):<|fim▁hole|> Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined()<|fim▁end|>
"""
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): <|fim_middle|> def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): <|fim_middle|> def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex]
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): <|fim_middle|> def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): <|fim_middle|> class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): <|fim_middle|> class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth)
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): <|fim_middle|> class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth)
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): <|fim_middle|> class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): <|fim_middle|> class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): <|fim_middle|> class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): <|fim_middle|> class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): <|fim_middle|> def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): <|fim_middle|> def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): <|fim_middle|> # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
""" Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): <|fim_middle|> <|fim▁end|>
""" Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): <|fim_middle|> <|fim▁end|>
""" Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined()
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: <|fim_middle|> if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
return -10
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: <|fim_middle|> if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
return 3
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: <|fim_middle|> return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
return 10
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def <|fim_middle|>(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
getAction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def <|fim_middle|>(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
evaluationFunction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def <|fim_middle|>(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
scoreEvaluationFunction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def <|fim_middle|>(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
__init__
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def <|fim_middle|>(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
getAction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def <|fim_middle|>(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
getAction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def <|fim_middle|>(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
getAction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def <|fim_middle|>(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def getAction(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
betterEvaluationFunction
<|file_name|>multiAgents.py<|end_file_name|><|fim▁begin|># multiAgents.py # -------------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to # http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html # # Attribution Information: The Pacman AI projects were developed at UC Berkeley. # The core projects and autograders were primarily created by John DeNero # ([email protected]) and Dan Klein ([email protected]). # Student side autograding was added by Brad Miller, Nick Hay, and # Pieter Abbeel ([email protected]). from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" ghost = str(newGhostStates[0]) ghost = ghost[ghost.find('=') + 1 : ghost.rfind(',')] ghost = ghost.replace(".0", "") #print newPos, newGhostStates[0] if str(newPos) == ghost: return -10 if newFood[newPos[0]][newPos[1]]: return 3 if newScaredTimes[0] > 0: return 10 return successorGameState.getScore() def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" util.raiseNotDefined() class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" util.raiseNotDefined() def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" util.raiseNotDefined() # Abbreviation better = betterEvaluationFunction class ContestAgent(MultiAgentSearchAgent): """ Your agent for the mini-contest """ def <|fim_middle|>(self, gameState): """ Returns an action. You can use any method you want and search to any depth you want. Just remember that the mini-contest is timed, so you have to trade off speed and computation. Ghosts don't behave randomly anymore, but they aren't perfect either -- they'll usually just make a beeline straight towards Pacman (or away from him if they're scared!) """ "*** YOUR CODE HERE ***" util.raiseNotDefined() <|fim▁end|>
getAction
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. #<|fim▁hole|>from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription")<|fim▁end|>
# See LICENSE file for full license. from .aws import Action as BaseAction
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): <|fim_middle|> class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription") <|fim▁end|>
def __init__(self, action: str = None) -> None: super().__init__(prefix, action)
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def __init__(self, action: str = None) -> None: <|fim_middle|> class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription") <|fim▁end|>
super().__init__(prefix, action)
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): <|fim_middle|> AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription") <|fim▁end|>
def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account )
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: <|fim_middle|> AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription") <|fim▁end|>
super().__init__( service=prefix, resource=resource, region=region, account=account )
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def <|fim_middle|>(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription") <|fim▁end|>
__init__
<|file_name|>shield.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012-2021, Mark Peek <[email protected]> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Shield" prefix = "shield" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def <|fim_middle|>(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account ) AssociateDRTLogBucket = Action("AssociateDRTLogBucket") AssociateDRTRole = Action("AssociateDRTRole") AssociateHealthCheck = Action("AssociateHealthCheck") AssociateProactiveEngagementDetails = Action("AssociateProactiveEngagementDetails") CreateProtection = Action("CreateProtection") CreateProtectionGroup = Action("CreateProtectionGroup") CreateSubscription = Action("CreateSubscription") DeleteProtection = Action("DeleteProtection") DeleteProtectionGroup = Action("DeleteProtectionGroup") DeleteSubscription = Action("DeleteSubscription") DescribeAttack = Action("DescribeAttack") DescribeAttackStatistics = Action("DescribeAttackStatistics") DescribeDRTAccess = Action("DescribeDRTAccess") DescribeEmergencyContactSettings = Action("DescribeEmergencyContactSettings") DescribeProtection = Action("DescribeProtection") DescribeProtectionGroup = Action("DescribeProtectionGroup") DescribeSubscription = Action("DescribeSubscription") DisableApplicationLayerAutomaticResponse = Action( "DisableApplicationLayerAutomaticResponse" ) DisableProactiveEngagement = Action("DisableProactiveEngagement") DisassociateDRTLogBucket = Action("DisassociateDRTLogBucket") DisassociateDRTRole = Action("DisassociateDRTRole") DisassociateHealthCheck = Action("DisassociateHealthCheck") EnableApplicationLayerAutomaticResponse = Action( "EnableApplicationLayerAutomaticResponse" ) EnableProactiveEngagement = Action("EnableProactiveEngagement") GetSubscriptionState = Action("GetSubscriptionState") ListAttacks = Action("ListAttacks") ListProtectionGroups = Action("ListProtectionGroups") ListProtections = Action("ListProtections") ListResourcesInProtectionGroup = Action("ListResourcesInProtectionGroup") ListTagsForResource = Action("ListTagsForResource") TagResource = Action("TagResource") UntagResource = Action("UntagResource") UpdateApplicationLayerAutomaticResponse = Action( "UpdateApplicationLayerAutomaticResponse" ) UpdateEmergencyContactSettings = Action("UpdateEmergencyContactSettings") UpdateProtectionGroup = Action("UpdateProtectionGroup") UpdateSubscription = Action("UpdateSubscription") <|fim▁end|>
__init__
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''):<|fim▁hole|> self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s<|fim▁end|>
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto i<|fim_middle|> <|fim▁end|>
dMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) s<|fim_middle|> eto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
elf.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, obj
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(o<|fim_middle|> s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
bjeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros):
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.t<|fim_middle|> ------------------------------------------- # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
itulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # -----------------------------
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIB<|fim_middle|> <|fim▁end|>
LIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante <|fim_middle|> '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante =
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] <|fim_middle|> = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
partes = partes.rpartition(" (") partes = partes[0] else: self.natureza
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux <|fim_middle|> (?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
= re.findall(u' (
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip( <|fim_middle|> self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
).rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = ''
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.tit <|fim_middle|> strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
ulo = partes.
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.a <|fim_middle|> eto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
utores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, obj
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembr <|fim_middle|> None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
o) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores i <|fim_middle|> .titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
f len(self.titulo)<len(objeto
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if <|fim_middle|> to.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
len(self.natureza)<len(obje
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza <|fim_middle|> lares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
return self else: # nao simi
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, lista <|fim_middle|> s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
DeMembros):
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, pa<|fim_middle|>em='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
rtesDoIt
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): <|fim_middle|>embro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
if self.idM
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = s<|fim_middle|>autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIPO DE PRODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
elf.
<|file_name|>outroTipoDeProducaoBibliografica.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # encoding: utf-8 # filename: outroTipoDeProducaoBibliografica.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from geradorDePaginasWeb import * import re class OutroTipoDeProducaoBibliografica: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de producao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)\.$', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u' ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(" ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".").rstrip(",") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[OUTRO TIP<|fim_middle|>ODUCAO BIBLIOGRAFICA] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s <|fim▁end|>
O DE PR
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # django-simple-help # simple_help/admin.py<|fim▁hole|> from __future__ import unicode_literals from django.contrib import admin try: # add modeltranslation from modeltranslation.translator import translator from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin except ImportError: pass from simple_help.models import PageHelp from simple_help.forms import PageHelpAdminForm from simple_help.utils import modeltranslation try: from simple_help.translation import PageHelpTranslationOptions except ImportError: pass __all__ = [ "PageHelpAdmin", ] class PageHelpAdmin(TabbedDjangoJqueryTranslationAdmin if modeltranslation() else admin.ModelAdmin): """ Customize PageHelp model for admin area. """ list_display = ["page", "title", ] search_fields = ["title", ] list_filter = ["page", ] form = PageHelpAdminForm if modeltranslation(): # registering translation options translator.register(PageHelp, PageHelpTranslationOptions) # registering admin custom classes admin.site.register(PageHelp, PageHelpAdmin)<|fim▁end|>
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # django-simple-help # simple_help/admin.py from __future__ import unicode_literals from django.contrib import admin try: # add modeltranslation from modeltranslation.translator import translator from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin except ImportError: pass from simple_help.models import PageHelp from simple_help.forms import PageHelpAdminForm from simple_help.utils import modeltranslation try: from simple_help.translation import PageHelpTranslationOptions except ImportError: pass __all__ = [ "PageHelpAdmin", ] class PageHelpAdmin(TabbedDjangoJqueryTranslationAdmin if modeltranslation() else admin.ModelAdmin): <|fim_middle|> if modeltranslation(): # registering translation options translator.register(PageHelp, PageHelpTranslationOptions) # registering admin custom classes admin.site.register(PageHelp, PageHelpAdmin) <|fim▁end|>
""" Customize PageHelp model for admin area. """ list_display = ["page", "title", ] search_fields = ["title", ] list_filter = ["page", ] form = PageHelpAdminForm
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # django-simple-help # simple_help/admin.py from __future__ import unicode_literals from django.contrib import admin try: # add modeltranslation from modeltranslation.translator import translator from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin except ImportError: pass from simple_help.models import PageHelp from simple_help.forms import PageHelpAdminForm from simple_help.utils import modeltranslation try: from simple_help.translation import PageHelpTranslationOptions except ImportError: pass __all__ = [ "PageHelpAdmin", ] class PageHelpAdmin(TabbedDjangoJqueryTranslationAdmin if modeltranslation() else admin.ModelAdmin): """ Customize PageHelp model for admin area. """ list_display = ["page", "title", ] search_fields = ["title", ] list_filter = ["page", ] form = PageHelpAdminForm if modeltranslation(): # registering translation options <|fim_middle|> # registering admin custom classes admin.site.register(PageHelp, PageHelpAdmin) <|fim▁end|>
translator.register(PageHelp, PageHelpTranslationOptions)
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate):<|fim▁hole|> Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64')))<|fim▁end|>
""" Verify if the received data was signed by the owner of the certificate.
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): <|fim_middle|> <|fim▁end|>
""" Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64')))
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): <|fim_middle|> def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key)
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): <|fim_middle|> self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Callback for private key decrypting. """ return str(passphrase.encode('utf-8'))
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): <|fim_middle|> def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex')
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): <|fim_middle|> def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding)
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): <|fim_middle|> def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64')
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): <|fim_middle|> def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex')
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): <|fim_middle|> def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64')
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): <|fim_middle|> def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64')
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): <|fim_middle|> def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey())
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): <|fim_middle|> def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey())
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): <|fim_middle|> def validSignedEncryptedData(self, cipherData, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) <|fim▁end|>
""" Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64')))
<|file_name|>CertAuthority.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ This module provides the necessary methods for a Certification Authority. For creating the self signed Certificate for the CA, use the following command: $ openssl req -x509 -newkey rsa:2048 -keyout ca_priv.pem -out ca_cert.pem @author: Vasco Santos """ import time from M2Crypto import X509, RSA, EVP, BIO, ASN1 class CertificationAuthority(object): """ Class responsible for keeping the CA self-signed certificate, as well as, its private key. """ def __init__(self, cert, priv_key, passphrase): """ Create a Certification Authority Object. Arguments: cert: file system path of the CA's self-signed certificate. priv_key: file system path of the CA's private key (encrypted). passphrase: Symmetric key for priv_key decryption. """ def getPassphrase(*args): """ Callback for private key decrypting. """ return str(passphrase.encode('utf-8')) self.cert = X509.load_cert(cert.encode('utf-8')) self.priv_key = RSA.load_key(priv_key.encode('utf-8'), getPassphrase) # Private key for signing self.signEVP = EVP.PKey() self.signEVP.assign_rsa(self.priv_key) def createSignedCertificate(self, subj_id, pub_key, expiration_time): """ Create a certificate for a subject public key, signed by the CA. Arguments: subj_id: certificate subject identifier. pub_key: public key of the subject. expiration_time: certificate life time. Returns: Certificate in PEM Format. """ # Public Key to certificate bio = BIO.MemoryBuffer(str(pub_key.decode('hex'))) pub_key = RSA.load_pub_key_bio(bio) pkey = EVP.PKey() pkey.assign_rsa(pub_key) # Certificate Fields cur_time = ASN1.ASN1_UTCTIME() cur_time.set_time(int(time.time())) expire_time = ASN1.ASN1_UTCTIME() expire_time.set_time(int(time.time()) + expiration_time * 60) # In expiration time minutes # Certification Creation cert = X509.X509() cert.set_pubkey(pkey) s_name = X509.X509_Name() s_name.C = "PT" s_name.CN = str(subj_id) cert.set_subject(s_name) i_name = X509.X509_Name() i_name.C = "PT" i_name.CN = "Register Server" cert.set_issuer_name(i_name) cert.set_not_before(cur_time) cert.set_not_after(expire_time) cert.sign(self.signEVP, md="sha1") #cert.save_pem("peer_CA.pem") return cert.as_pem().encode('hex') def decryptData(self, data): """ Decrypt the intended data with the entity private key. Arguments: data: data to be decrypted. """ return self.priv_key.private_decrypt(data.decode('base64'), RSA.pkcs1_padding) def encryptData(self, data, certificate): """ Encrypt the intended data with the public key contained in the certificate. Arguments: data: data to be encrypted. certificate: subject certificate. """ cert = X509.load_cert_string(certificate.decode('hex')) return cert.get_pubkey().get_rsa().public_encrypt(str(data), RSA.pkcs1_padding).encode('base64') def getPublicKey(self): """ Get the CA Public Key. Returns: CA Public Key in PEM Format. """ return self.cert.get_pubkey().get_rsa().as_pem().encode('hex') def signData(self, data): """ Sign a received String. Arguments: data: string to sign. Returns: signature of the received data. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def signEncryptedData(self, cipherData): """ Sign encrypted data. Arguments: cipherData: data encrypted (base64 format). """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) self.signEVP.sign_init() self.signEVP.sign_update(msgDigest.digest()) return self.signEVP.sign_final().encode('base64') def validCertificate(self, certificate): """ Verify if a certificate of a subject was issued by this CA. Arguments: certificate: subject certificate. Returns: true if the certificate was issued by this CA. false otherwise. """ cert = X509.load_cert_string(certificate.decode('hex')) # Data Analysis # Subject confirmation return cert.verify(self.cert.get_pubkey()) def validSelfSignedCertificate(self): """ Verify if the self-signed CA certificate was not corrupted. Returns: true if the self signed certificate is valid, false otherwise. """ return self.cert.check_ca() and self.cert.verify(self.cert.get_pubkey()) def validSignedData(self, data, signature, certificate): """ Verify if the received data was signed by the owner of the certificate. Arguments: data: received data. signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(str(data)) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64'))) def validSignedEncryptedData(self, cipherData, signature, certificate): <|fim_middle|> <|fim▁end|>
""" Verify if the received data was signed by the owner of the certificate. Arguments: cipherData: data encrypted (base64 format). signature: digital signature of the data. certificate: certificate of the data issuer. Returns: true if the data maintains its integrity, false otherwise. """ msgDigest = EVP.MessageDigest('sha1') msgDigest.update(cipherData.decode('base64')) pub_key = X509.load_cert_string(certificate.decode('hex')).get_pubkey().get_rsa() verifyEVP = EVP.PKey() verifyEVP.assign_rsa(pub_key) verifyEVP.verify_init() verifyEVP.verify_update(msgDigest.digest()) return verifyEVP.verify_final(str(signature.decode('base64')))