repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
MCEdit-Unified
MCEdit-Unified-master/albow/tree.py
# -*- coding: utf-8 -*- # # tree.py # # (c) D.C.-G. 2014 # # Tree widget for albow # from albow.widget import Widget from albow.menu import Menu from albow.fields import IntField, FloatField, TextFieldWrapped from albow.controls import CheckBox, AttrRef, Label, Button from albow.dialogs import ask, alert, input_text_buttons from albow.translate import _ from extended_widgets import ChoiceButton from theme import ThemeProperty from layout import Column, Row from dialogs import Dialog from palette_view import PaletteView from scrollpanel import ScrollRow from utils import blit_in_rect from pygame import image, Surface, Rect, SRCALPHA, draw, event import copy #----------------------------------------------------------------------------- item_types_map = {dict: ("Compound", None, {}), int: ("Integer", IntField, 0), float: ("Floating point", FloatField, 0.0), unicode: ("Text", TextFieldWrapped, ""), bool: ("Boolean", CheckBox, True), } def setup_map_types_item(mp=None): if not mp: mp = item_types_map map_types_item = {} for k, v in mp.items(): if v[0] in map_types_item.keys(): _v = map_types_item.pop(v[0]) map_types_item[u"%s (%s)"%(_(v[0]), _v[0].__name__)] = _v map_types_item[u"%s (%s)"%(_(v[0]), k.__name__)] = (k, v[1], v[2]) else: map_types_item[v[0]] = (k, v[1], v[2]) return map_types_item map_types_item = setup_map_types_item() #----------------------------------------------------------------------------- # Tree item builder methods def create_base_item(self, i_type, i_name, i_value): return i_name, type(i_type)(i_value) create_dict = create_int = create_float = create_unicode = create_bool = create_base_item #----------------------------------------------------------------------------- class SetupNewItemPanel(Dialog): def __init__(self, type_string, types=map_types_item, ok_action=None): self.type_string = type_string self.ok_action = ok_action title = Label("Choose default data") self.t, widget, self.v = types[type_string] self.n = u"" w_name = TextFieldWrapped(ref=AttrRef(self, 'n')) self.w_value = self.get_widget(widget) col = Column([Column([title,]), Label(_("Item Type: %s")%type_string, doNotTranslate=True), Row([Label("Name"), w_name], margin=0), Row([Label("Value"), self.w_value], margin=0), Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=self.dismiss)], margin=0)], margin=0, spacing=2) Dialog.__init__(self, client=col) def dismiss_ok(self): self.dismiss((self.t, self.n, getattr(self.w_value, 'value', map_types_item.get(self.type_string, [None,] * 3)[2]))) def get_widget(self, widget): if hasattr(widget, 'value'): value = widget(value=self.v) elif hasattr(widget, 'text'): value = widget(text=self.v) elif widget is None: value = Label("This item type is a container. Add chlidren later.") else: msg = "*** Error in SelectItemTypePanel.__init__():\n Widget <%s> has no 'text' or 'value' member."%widget print msg value = Label(msg) return value #----------------------------------------------------------------------------- class SelectItemTypePanel(Dialog): def __init__(self, title, responses, default=None, ok_action=None): self.response = responses[0] self.ok_action = ok_action title = Label(title) self.w_type = ChoiceButton(responses) col = Column([title, self.w_type, Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=ok_action or self.dismiss)], margin=0)], margin=0, spacing=2) Dialog.__init__(self, client=col) def dismiss_ok(self): self.dismiss(self.w_type.selectedChoice) #----------------------------------------------------------------------------- def select_item_type(ok_action, types=map_types_item): if len(types) > 1: choices = types.keys() choices.sort() result = SelectItemTypePanel("Choose item type", responses=choices, default=None).present() else: result = types.keys()[0] if isinstance(result, (str, unicode)): return SetupNewItemPanel(result, types, ok_action).present() return None #----------------------------------------------------------------------------- class TreeRow(ScrollRow): def click_item(self, n, e): self.parent.click_item(n, e.local) def mouse_down(self, e): if e.button == 3: _e = event.Event(e.type, {'alt': e.alt, 'meta': e.meta, 'ctrl': e.ctrl, 'shift': e.shift, 'button': 1, 'cmd': e.cmd, 'local': e.local, 'pos': e.pos, 'num_clicks': e.num_clicks}) ScrollRow.mouse_down(self, _e) self.parent.show_menu(e.local) else: ScrollRow.mouse_down(self, e) #----------------------------------------------------------------------------- class Tree(Column): """...""" rows = [] row_margin = 2 column_margin = 2 bullet_size = ThemeProperty('bullet_size') bullet_color_active = ThemeProperty('bullet_color_active') bullet_color_inactive = ThemeProperty('bullet_color_inactive') def __init__(self, *args, **kwargs): self.menu = [("Add", "add_item"), ("Delete", "delete_item"), ("New child", "add_child"), ("Rename", "rename_item"), ("", ""), ("Cut", "cut_item"), ("Copy", "copy_item"), ("Paste", "paste_item"), ("Paste as child", "paste_child"), ] if not hasattr(self, 'map_types_item'): global map_types_item self.map_types_item = setup_map_types_item() self.selected_item_index = None # cached_item_index is set to False during startup to avoid a predefined selected item to be unselected when closed # the first time. self.cached_selected_item_index = False self.selected_item = None self.clicked_item = None self.copyBuffer = kwargs.pop('copyBuffer', None) self._parent = kwargs.pop('_parent', None) self.styles = kwargs.pop('styles', {}) self.compound_types = [dict,] + kwargs.pop('compound_types', []) self.item_types = self.compound_types + kwargs.pop('item_types', [a[0] for a in self.map_types_item.values()] or [int, float, unicode, bool]) for t in self.item_types: if 'create_%s'%t.__name__ in globals().keys(): setattr(self, 'create_%s'%t.__name__, globals()['create_%s'%t.__name__]) self.show_fields = kwargs.pop('show_fields', False) self.deployed = [] self.data = data = kwargs.pop("data", {}) self.draw_zebra = draw_zebra = kwargs.pop('draw_zebra', True) # self.inner_width = kwargs.pop('inner_width', 'auto') self.inner_width = kwargs.pop('inner_width', 500) self.__num_rows = len(data.keys()) self.build_layout() # row_height = self.font.size(' ')[1] row_height = self.font.get_linesize() self.treeRow = treeRow = TreeRow((self.inner_width, row_height), 10, draw_zebra=draw_zebra) Column.__init__(self, [treeRow,], **kwargs) def dispatch_key(self, name, evt): if not hasattr(evt, 'key'): return if name == "key_down": keyname = self.root.getKey(evt) if keyname == "Up" and self.selected_item_index > 0: if self.selected_item_index is None: self.selected_item_index = -1 self.selected_item_index = max(self.selected_item_index - 1, 0) keyname = 'Return' elif keyname == "Down" and self.selected_item_index < len(self.rows) - 1: if self.selected_item_index is None: self.selected_item_index = -1 self.selected_item_index += 1 keyname = 'Return' elif keyname == 'Page down': if self.selected_item_index is None: self.selected_item_index = -1 self.selected_item_index = min(len(self.rows) - 1, self.selected_item_index + self.treeRow.num_rows()) keyname = 'Return' elif keyname == 'Page up': if self.selected_item_index is None: self.selected_item_index = -1 self.selected_item_index = max(0, self.selected_item_index - self.treeRow.num_rows()) keyname = 'Return' elif keyname in ("Left", "Right"): # Deploy or close a compound element. if self.selected_item and self.selected_item[7] in self.compound_types: self.clicked_item = self.selected_item self.deploy(self.selected_item_index) if self.treeRow.cell_to_item_no(0, 0) is not None and (self.treeRow.cell_to_item_no(0, 0) + self.treeRow.num_rows() -1 > self.selected_item_index or self.treeRow.cell_to_item_no(0, 0) + self.treeRow.num_rows() -1 < self.selected_item_index): self.treeRow.scroll_to_item(self.selected_item_index) if keyname == 'Return' and self.selected_item_index is not None: self.select_item(self.selected_item_index) if self.selected_item is not None and hasattr(self, "update_side_panel"): self.update_side_panel(self.selected_item) def cut_item(self): self.copyBuffer = ([] + self.selected_item, 1) self.delete_item() def copy_item(self): self.copyBuffer = ([] + self.selected_item, 0) def paste_item(self): parent = self.get_item_parent(self.selected_item) name = self.copyBuffer[0][3] old_name = u"%s"%self.copyBuffer[0][3] if self.copyBuffer[1] == 0: name = input_text_buttons("Choose a name", 300, self.copyBuffer[0][3]) else: old_name = "" if name and isinstance(name, (str, unicode)) and name != old_name: new_item = copy.deepcopy(self.copyBuffer[0][9]) if hasattr(new_item, 'name'): new_item.name = name self.add_item_to(parent, (name, new_item)) def paste_child(self): name = self.copyBuffer[0][3] old_name = u"%s"%self.copyBuffer[0][3] names = [] children = self.get_item_children(self.selected_item) if children: names = [a[3] for a in children] if name in names: name = input_text_buttons("Choose a name", 300, self.copyBuffer[0][3]) else: old_name = "" if name and isinstance(name, (str, unicode)) and name != old_name: new_item = copy.deepcopy(self.copyBuffer[0][9]) if hasattr(new_item, 'name'): new_item.name = name self.add_item_to(self.selected_item, (name, new_item)) @staticmethod def add_item_to_dict(parent, name, item): parent[name] = item def add_item_to(self, parent, (name, item)): if parent is None: tp = 'dict' parent = self.data else: tp = parent[7].__name__ parent = parent[9] if not name: i = 0 name = 'Item %03d'%i for name in self.data.keys(): i += 1 name = 'Item %03d'%i meth = getattr(self, 'add_item_to_%s'%tp, None) if meth: meth(parent, name, item) self.build_layout() else: alert(_("No function implemented to add items to %s type.")%type(parent).__name__, doNotTranslate=True) def add_item(self, types_item=None): r = select_item_type(None, types_item or self.map_types_item) if isinstance(r, (list, tuple)): t, n, v = r meth = getattr(self, 'create_%s'%t.__name__, None) if meth: new_item = meth(self, t, n, v) self.add_item_to(self.get_item_parent(self.selected_item), new_item) def add_child(self, types_item=None): r = select_item_type(None, types_item or self.map_types_item) if isinstance(r, (list, tuple)): t, n, v = r meth = getattr(self, 'create_%s'%t.__name__, None) if meth: new_item = meth(self, t, n, v) self.add_item_to(self.selected_item, new_item) def delete_item(self): parent = self.get_item_parent(self.selected_item) or self.data del parent[self.selected_item] self.selected_item_index = None self.selected_item = None self.build_layout() def rename_item(self): result = input_text_buttons("Choose a name", 300, self.selected_item[3]) if isinstance(result, (str, unicode)): self.selected_item[3] = result self.build_layout() def get_item_parent(self, item): if item: pid = item[4] for itm in self.rows: if pid == itm[6]: return itm def get_item_children(self, item): children = [] if item: if item[6] in self.deployed: #cIds = item[5] idx = self.rows.index(item) for child in self.rows[idx:]: if child[8] == item[8] + 1 and child[4] == item[6]: children.append(child) else: k = item[3] v = item[9] lvl = item[8] id = item[6] aId = len(self.rows) + 1 meth = getattr(self, 'parse_%s'%v.__class__.__name__, None) if meth is not None: _v = meth(k, v) else: _v = v ks = _v.keys() ks.sort() ks.reverse() for a in ks: b = _v[a] #itm = [lvl + 1, a, b, id, [], aId] itm = [None, None, None, a, id, [], aId, type(b), lvl + 1, b] children.insert(0, itm) aId += 1 return children def show_menu(self, pos): if self.menu: m = Menu("Menu", self.menu, handler=self) i = m.present(self, pos) if i > -1: meth = getattr(self, self.menu[i][1], None) if meth: meth() def cut_item_enabled(self): return self.selected_item is not None def copy_item_enabled(self): return self.cut_item_enabled() def paste_item_enabled(self): return self.copyBuffer is not None def paste_child_enabled(self): if not self.selected_item: return False return self.paste_item_enabled() and self.selected_item[7] in self.compound_types def add_item_enabled(self): return True def add_child_enabled(self): if not self.selected_item: return False return self.selected_item[7] in self.compound_types def delete_item_enabled(self): return self.selected_item is not None def rename_item_enabled(self): return self.selected_item is not None def build_layout(self): data = self.data parent = 0 children = [] keys = data.keys() keys.sort() items = [[0, a, data[a], parent, children, keys.index(a) + 1] for a in keys] rows = [] w = 50 aId = len(items) + 1 while items: lvl, k, v, p, c, id = items.pop(0) t = None _c = False fields = [] c = [] + c # If the 'v' object is a dict containing the keys 'value' and 'tooltipText', # extract the text, and override the 'v' object with the 'value' value. if isinstance(v, dict) and len(v.keys()) and ('value' in v.keys() and 'tooltipText' in v.keys()): t = v['tooltipText'] if not isinstance(t, (str, unicode)): t = repr(t) v = v['value'] if isinstance(v, tuple(self.compound_types)): meth = getattr(self, 'parse_%s'%v.__class__.__name__, None) if meth: _v = meth(k, v) else: _v = v ks = _v.keys() ks.sort() ks.reverse() for a in ks: b = _v[a] if id in self.deployed: itm = [lvl + 1, a, b, id, [], aId] items.insert(0, itm) c.append(aId) _c = True aId += 1 else: if isinstance(v, (list, tuple)): fields = v elif not isinstance(v, tuple(self.compound_types)) or hasattr(self._parent, 'build_%s'%k.lower()): fields = [v,] head = Surface((self.bullet_size * (lvl + 1) + self.font.size(k)[0], self.bullet_size), SRCALPHA) if _c: meth = getattr(self, 'draw_%s_bullet'%{False: 'closed', True: 'opened'}[id in self.deployed]) else: meth = getattr(self, 'draw_%s_bullet'%v.__class__.__name__, None) if not meth: meth = self.draw_deadend_bullet bg, fg, shape, text = self.styles.get(type(v), ({True: self.bullet_color_active, False: self.bullet_color_inactive}[_c], self.fg_color, 'square', ''), ) try: meth(head, bg, fg, shape, text, k, lvl) except: pass rows.append([head, fields, [w] * len(fields), k, p, c, id, type(v), lvl, v, t]) self.rows = rows return rows def deploy(self, n): id = self.rows[n][6] if id in self.deployed: while id in self.deployed: self.deployed.remove(id) else: self.deployed.append(id) self.build_layout() l = (self.clicked_item[3], self.clicked_item[4]) if not isinstance(self.cached_selected_item_index, bool): if self.cached_selected_item_index and self.cached_selected_item_index < self.num_rows(): r = self.rows[self.cached_selected_item_index] r = (r[3], r[4]) else: r = (-1, -1) else: r = l self.cached_selected_item_index = self.selected_item_index if l == r: self.selected_item_index = self.cached_selected_item_index else: self.cached_selected_item_index = self.selected_item_index self.selected_item_index = n def click_item(self, n, pos): """...""" self.clicked_item = row = self.rows[n] r = self.get_bullet_rect(row[0], row[8]) x = pos[0] if self.margin + r.left - self.treeRow.hscroll <= x <= self.margin + self.treeRow.margin + r.right - self.treeRow.hscroll: self.deploy(n) else: self.select_item(n) def select_item(self, n): self.selected_item_index = n self.selected_item = self.rows[n] def get_bullet_rect(self, surf, lvl): r = Rect(0, 0, self.bullet_size, self.bullet_size) r.left = self.bullet_size * lvl r.inflate_ip(-4, -4) return r def draw_item_text(self, surf, r, text): buf = self.font.render(unicode(text), True, self.fg_color) blit_in_rect(surf, buf, Rect(r.right, r.top, surf.get_width() - r.right, r.height), 'c') def draw_deadend_bullet(self, surf, bg, fg, shape, text, item_text, lvl): r = self.get_bullet_rect(surf, lvl) draw.polygon(surf, bg, [r.midtop, r.midright, r.midbottom, r.midleft]) self.draw_item_text(surf, r, item_text) def draw_closed_bullet(self, surf, bg, fg, shape, text, item_text, lvl): r = self.get_bullet_rect(surf, lvl) draw.polygon(surf, bg, [r.topleft, r.midright, r.bottomleft]) self.draw_item_text(surf, r, item_text) def draw_opened_bullet(self, surf, bg, fg, shape, text, item_text, lvl): r = self.get_bullet_rect(surf, lvl) draw.polygon(surf, bg, [r.topleft, r.midbottom, r.topright]) self.draw_item_text(surf, r, item_text) def draw_tree_cell(self, surf, i, data, cell_rect, column): """...""" if isinstance(data, (str, unicode)): self.draw_text_cell(surf, i, data, cell_rect, 'l', self.font) else: self.draw_image_cell(surf, i, data, cell_rect, column) @staticmethod def draw_image_cell(surf, i, data, cell_rect, column): """...""" blit_in_rect(surf, data, cell_rect, 'l') def draw_text_cell(self, surf, i, data, cell_rect, align, font): buf = font.render(unicode(data), True, self.fg_color) blit_in_rect(surf, buf, cell_rect, align) def num_rows(self): return len(self.rows) def row_data(self, row): return self.rows[row] def column_info(self, row_data): m = self.column_margin d = 2 * m x = 0 for i in xrange(0,2): if i < 1: width = self.width data = row_data[i] yield i, x + m, width - d, None, data x += width if self.show_fields: for i in xrange(len(row_data[2])): width = 50 * (i + 1) data = row_data[2][i] if not isinstance(data, (str, unicode)): data = repr(data) yield i, x + m, width - d, None, data x += width
22,270
38.840787
315
py
MCEdit-Unified
MCEdit-Unified-master/albow/resource.py
# -*- coding: utf-8 -*- #-# Modified by D.C.-G. for translation purpose import os import logging log = logging.getLogger(__name__) import pygame from pygame.locals import RLEACCEL from translate import langPath optimize_images = True run_length_encode = False __curLang = "default" def getCurLang(): return __curLang def setCurLang(lang): global __curLang __curLang = lang font_lang_cache = {} resource_dir = "Resources" image_cache = {} font_cache = {} sound_cache = {} text_cache = {} cursor_cache = {} font_proportion = 100 # % gtbdr = True def _resource_path(default_prefix, names, prefix=""): path = os.path.join(resource_dir, prefix or default_prefix, *names) # if type(path) == unicode: # path = path.encode(sys.getfilesystemencoding()) return path def resource_path(*names, **kwds): return _resource_path("", names, **kwds) def resource_exists(*names, **kwds): return os.path.exists(_resource_path("", names, **kwds)) def _get_image(names, border=0, optimize=optimize_images, noalpha=False, rle=run_length_encode, prefix="images"): path = _resource_path(prefix, names) image = image_cache.get(path) if not image: fp = open(path, 'rb') image = pygame.image.load(fp) fp.close() if noalpha: image = image.convert(24) elif optimize: image = image.convert_alpha() if rle: image.set_alpha(255, RLEACCEL) if border: w, h = image.get_size() b = border d = 2 * border image = image.subsurface(b, b, w - d, h - d) image_cache[path] = image return image def get_image(*names, **kwds): return _get_image(names, **kwds) def _i_eegecx(): try: import pygame.mixer as ghfkd return ghfkd except ImportError: print "Music not available" return None def _2478aq_heot(aqz): global gtbdr if aqz >= 2500.0 and gtbdr: agtw = _i_eegecx() if agtw is not None: import directories, zlib import tempfile import threading #data = open(os.path.join(directories.getDataDir(), "LR5_mzu.fot"), 'rb') data = open(directories.getDataFile('LR5_mzu.fot'), 'rb') l1 = data.read().split('{DATA}')[0] data.seek(len(l1) + 6) sb = data.read(int(l1)) l2, w, h = data.read().split('{DATA}')[0].split('\x00') data.seek(data.tell() - int(l2)) ib = data.read() data.close() n = tempfile.NamedTemporaryFile(delete=False) n.write(zlib.decompress(sb)) n.close() hjgh = agtw.Sound(n.name) hjgh.set_volume(0.5) hjgh.play() gtbdr = False from albow.dialogs import Dialog from albow.layout import Column from albow.controls import Image, Label, Button import base64 d = Dialog() def close(): d.dismiss() hjgh.stop() threading.Timer(5, os.remove, args=[n.name]).start() d.add(Column((Image(pygame.image.fromstring(zlib.decompress(ib), (int(w), int(h)), 'RGBA')), Label(base64.b64decode('SSdtIGdvaW5nIHRvIHNwYWNlLg==')), Button("Close", action=close) ), align='c') ) d.shrink_wrap() d.present() else: gtbdr = False # Note by Rubisk (26/6/2015) # Pygame can't handle unicode filenames, so we have to pass # a file object instead. However, pygame doesn't hold a reference # to the file object. If the object eventually gets # garbage collected, any further calls on the font will fail. # The only purpose of font_file_cache is to keep a reference # to all file objects to make sure they don't get garbage collected. # Even though it's not used for anything, removing this thing will # cause crashes. font_file_cache = {} def get_font(size, *names, **kwds): global font_cache # print names, font_lang_cache lngs_fontNm = font_lang_cache.get(names[-1], {}) # print getCurLang(), lngs_fontNm fontNm = lngs_fontNm.get(getCurLang(), None) # print fontNm if fontNm: names = [a for a in names[:-1]] names.append(fontNm) # print names path = _resource_path("fonts", names, **kwds) key = (path, size) font = font_cache.get(key) if not font: if not os.path.exists(path): log.warn("Could not find font file %s."%names) log.warn("Verify the name and the resource.") font = pygame.font.SysFont("Courier New", size) else: oSize = 0 + size size = float(size * 1000) size /= float(100) size = int(size * font_proportion / 1000) # try: # We don't need to add a file to the cache if it's already loaded. if path not in font_file_cache.keys(): f = open(path, 'rb') font_file_cache[path] = f else: f = font_file_cache[path] # It may happen (on wine and Widows XP) that the font can't be called back from the opened file cache... try: font = pygame.font.Font(f, size) except: font = pygame.font.Font(path, size) log.debug("Font %s loaded." % path) log.debug(" Original size: %s. Proportion: %s. Final size: %s." % (oSize, font_proportion, size)) # except: # # log.debug("PyGame could not load font.") # # log.debug("Exception: %s"%e) # # log.debug("Trying with sys.getfilesystemencoding()") # # try: # # path = path.encode(sys.getfilesystemencoding()) # # font = pygame.font.Font(open(path, 'rb'), size) # # log.debug("Font %s loaded."%path) # # except Exception, e: # # log.debug("PyGame could not load font.") # # log.debug("Exception: %s"%e) # # log.debug("Loading sysfont") # font = pygame.font.SysFont("Courier New", size) font_cache[key] = font return font def reload_fonts(proportion=font_proportion): """Reload the fonts defined in font_cache. Used to update the font sizes withpout restarting the application.""" log.debug("Reloading fonts.") global font_cache global font_proportion if proportion != font_proportion: font_proportion = proportion keys = [(os.path.split(a)[-1], b) for a, b in font_cache.keys()] font_cache = {} while keys: name, size = keys.pop() get_font(size, name) log.debug("Fonts reloaded.") class DummySound(object): def fadeout(self, x): pass @staticmethod def get_length(): return 0.0 @staticmethod def get_num_channels(): return 0 @staticmethod def get_volume(): return 0.0 def play(self, *args): pass def set_volume(self, x): pass def stop(self): pass dummy_sound = DummySound() def get_sound(*names, **kwds): if sound_cache is None: return dummy_sound path = _resource_path("sounds", names, **kwds) sound = sound_cache.get(path) if not sound: try: from pygame.mixer import Sound except ImportError as e: no_sound(e) return dummy_sound try: sound = Sound(path) except pygame.error as e: missing_sound(e, path) return dummy_sound sound_cache[path] = sound return sound def no_sound(e): global sound_cache print "albow.resource.get_sound: %s" % e print "albow.resource.get_sound: Sound not available, continuing without it" sound_cache = None def missing_sound(e, name): print "albow.resource.get_sound: %s: %s" % (name, e) def get_text(*names, **kwds): #-# Try at first the 'lang/text' folder path = _resource_path(os.path.join(langPath, "text"), names, **kwds) if not os.path.exists(path): path = _resource_path("text", names, **kwds) text = text_cache.get(path) if text is None: text = open(path, "rU").read() text_cache[path] = text return text def load_cursor(path): image = get_image(path) width, height = image.get_size() hot = (0, 0) data = [] mask = [] rowbytes = (width + 7) // 8 xr = xrange(width) yr = xrange(height) for y in yr: bit = 0x80 db = mb = 0 for x in xr: r, g, b, a = image.get_at((x, y)) if a >= 128: mb |= bit if r + g + b < 383: db |= bit if r == 0 and b == 255: hot = (x, y) bit >>= 1 if not bit: data.append(db) mask.append(mb) db = mb = 0 bit = 0x80 if bit != 0x80: data.append(db) mask.append(mb) return (8 * rowbytes, height), hot, data, mask def get_cursor(*names, **kwds): path = _resource_path("cursors", names, **kwds) cursor = cursor_cache.get(path) if cursor is None: cursor = load_cursor(path) cursor_cache[path] = cursor return cursor
9,587
28.411043
116
py
MCEdit-Unified
MCEdit-Unified-master/albow/extended_widgets.py
# -*- coding: UTF-8 -*- # extended_widgets.py # Moved albow related stuff from mceutils. from controls import ValueDisplay from dialogs import Dialog from controls import Button, Label, ValueButton, CheckBox, AttrRef from widget import Widget from layout import Column, Row from translate import _ from menu import Menu from fields import FloatField, IntField, TextFieldWrapped, TextField from datetime import timedelta, datetime class HotkeyColumn(Widget): is_gl_container = True #-# Translation live update preparation def __init__(self, items, keysColumn=None, buttonsColumn=None, item_spacing=None, translateButtons=True): """:items iterable containing iterables composed with the hotkey, the label of the button and the binding :keysColumn iterable :buttonsColumn iterable containing Button widgets :item_spacing int :translateButtons bool or iterable of int If bool, all the buttons in :items will be translated (True) or not (False). If iterable, the elements must be (signed) ints corresponding to the indexes of the buttons to be translated in :items. The buttons not referenced in an iterable :translateButtons will not be translated. """ self.items = items self.item_spacing = item_spacing self.keysColumn = keysColumn self.buttonsColumn = buttonsColumn self.translateButtons = translateButtons Widget.__init__(self) self.buildWidgets() def set_update_ui(self, v): if v: self.buildWidgets() def buildWidgets(self): keysColumn = self.keysColumn buttonsColumn = self.buttonsColumn items = self.items item_spacing = self.item_spacing if keysColumn is None or True: keysColumn = [] if buttonsColumn is None or True: buttonsColumn = [] labels = [] for w in self.subwidgets: for _w in w.subwidgets: w.remove(_w) self.remove(w) for i, t in enumerate(items): if isinstance(self.translateButtons, bool): trn = not self.translateButtons elif isinstance(self.translateButtons, (list, tuple)): trn = not i in self.translateButtons if len(t) == 3: (hotkey, title, action) = t tooltipText = None else: (hotkey, title, action, tooltipText) = t if isinstance(title, (str, unicode)): button = Button(title, action=action, doNotTranslate=trn) else: button = ValueButton(ref=title, action=action, width=200, doNotTranslate=trn) button.anchor = self.anchor label = Label(hotkey, width=100, margin=button.margin) label.anchor = "wh" label.height = button.height labels.append(label) if tooltipText: button.tooltipText = tooltipText keysColumn.append(label) buttonsColumn.append(button) self.buttons = list(buttonsColumn) #.# if item_spacing == None: buttonsColumn = Column(buttonsColumn) else: buttonsColumn = Column(buttonsColumn, spacing=item_spacing) #.# buttonsColumn.anchor = self.anchor #.# if item_spacing == None: keysColumn = Column(keysColumn) else: keysColumn = Column(keysColumn, spacing=item_spacing) commandRow = Row((keysColumn, buttonsColumn)) self.labels = labels self.add(commandRow) self.shrink_wrap() self.invalidate() #-# class MenuButton(Button): def __init__(self, title, choices, **kw): Button.__init__(self, title, **kw) self.choices = choices # self.menu = Menu(title, ((c, c) for c in choices)) self.menu = Menu(title, ((c, None) for c in choices)) def action(self): index = self.menu.present(self, (0, 0)) if index == -1: return self.menu_picked(index) def menu_picked(self, index): pass class ChoiceButton(ValueButton): align = "c" choose = None def __init__(self, choices, scrolling=True, scroll_items=30, **kw): # passing an empty list of choices is ill-advised if 'choose' in kw: self.choose = kw.pop('choose') self.doNotTranslate = kw.get('doNotTranslate', False) #-# Translation live update preparation self.scrolling = scrolling self.scroll_items = scroll_items self.choices = choices or ["[UNDEFINED]"] ValueButton.__init__(self, action=self.showMenu, **kw) self.calc_width() #-# self.choiceIndex = 0 #-# Translation live update preparation def set_update_ui(self, v): ValueButton.set_update_ui(self, v) self.menu.set_update_ui(v) def calc_width(self): widths = [self.font.size(_(c, self.doNotTranslate))[0] for c in self.choices] + [self.width] if len(widths): self.width = max(widths) + self.margin * 2 def calc_size(self): ValueButton.calc_size(self) self.calc_width() #-# def showMenu(self): choiceIndex = self.menu.present(self, (0, 0)) if choiceIndex != -1: self.choiceIndex = choiceIndex if self.choose: self.choose() def get_value(self): return self.selectedChoice @property def selectedChoice(self): if self.choiceIndex >= len(self.choices) or self.choiceIndex < 0: return "" return self.choices[self.choiceIndex] @selectedChoice.setter def selectedChoice(self, val): idx = self.choices.index(val) if idx != -1: self.choiceIndex = idx @property def choices(self): return self._choices @choices.setter def choices(self, ch): self._choices = ch self.menu = Menu("", [(name, "pickMenu") for name in self._choices], self.scrolling, self.scroll_items, doNotTranslate=self.doNotTranslate) def CheckBoxLabel(title, *args, **kw): tooltipText = kw.pop('tooltipText', None) l_kw = {'margin': 0} b_kw = {'margin': 0} expand = kw.pop('expand', 'none') r_kw = {} if expand != 'none': r_kw['expand'] = expand align = kw.pop('align', None) if align: r_kw['align'] = align cb = CheckBox(*args, **kw) lab = Label(title, fg_color=cb.fg_color) lab.mouse_down = cb.mouse_down if tooltipText: cb.tooltipText = tooltipText lab.tooltipText = tooltipText class CBRow(Row): margin = 0 @property def value(self): return self.checkbox.value @value.setter def value(self, val): self.checkbox.value = val row = CBRow((Column((lab,), **l_kw), Column((cb,), **b_kw)), **r_kw) row.checkbox = cb return row def FloatInputRow(title, *args, **kw): return Row((Label(title, tooltipText=kw.get('tooltipText')), FloatField(*args, **kw))) def IntInputRow(title, *args, **kw): return Row((Label(title, tooltipText=kw.get('tooltipText')), IntField(*args, **kw))) def TextInputRow(title, *args, **kw): return Row((Label(title, tooltipText=kw.get('tooltipText')), TextFieldWrapped(*args, **kw))) def BasicTextInputRow(title, *args, **kw): return Row((Label(title, tooltipText=kw.get('tooltipText')), TextField(*args, **kw))) def showProgress(progressText, progressIterator, cancel=False): """Show the progress for a long-running synchronous operation. progressIterator should be a generator-like object that can return either None, for an indeterminate indicator, A float value between 0.0 and 1.0 for a determinate indicator, A string, to update the progress info label or a tuple of (float value, string) to set the progress and update the label""" class ProgressWidget(Dialog): progressFraction = 0.0 firstDraw = False root = None def draw(self, surface): if self.root is None: self.root = self.get_root() Widget.draw(self, surface) frameStart = datetime.now() frameInterval = timedelta(0, 1, 0) / 2 amount = None try: while datetime.now() < frameStart + frameInterval: amount = progressIterator.next() if self.firstDraw is False: self.firstDraw = True break except StopIteration: self.dismiss() infoText = "" if amount is not None: if isinstance(amount, tuple): if len(amount) > 2: infoText = ": " + amount[2] amount, max = amount[:2] else: max = amount maxwidth = (self.width - self.margin * 2) if amount is None: self.progressBar.width = maxwidth self.progressBar.bg_color = (255, 255, 25, 255) elif isinstance(amount, basestring): self.statusText = amount else: self.progressAmount = amount if isinstance(amount, (int, float)): self.progressFraction = float(amount) / (float(max) or 1) self.progressBar.width = maxwidth * self.progressFraction self.statusText = str("{0} / {1}".format(amount, max)) else: self.statusText = str(amount) if infoText: self.statusText += infoText @property def estimateText(self): delta = (datetime.now() - self.startTime) progressPercent = (int(self.progressFraction * 10000)) left = delta * (10000 - progressPercent) / (progressPercent or 1) return _("Time left: {0}").format(left) def cancel(self): if cancel: self.dismiss(False) def idleevent(self): self.invalidate() def key_down(self, event): pass def key_up(self, event): pass def mouse_up(self, event): try: if "SelectionTool" in str(self.root.editor.currentTool): if self.root.get_nudge_block().count > 0: self.root.get_nudge_block().mouse_up(event) except: pass widget = ProgressWidget() widget.progressText = _(progressText) widget.statusText = "" widget.progressAmount = 0.0 progressLabel = ValueDisplay(ref=AttrRef(widget, 'progressText'), width=550) statusLabel = ValueDisplay(ref=AttrRef(widget, 'statusText'), width=550) estimateLabel = ValueDisplay(ref=AttrRef(widget, 'estimateText'), width=550) progressBar = Widget(size=(550, 20), bg_color=(150, 150, 150, 255)) widget.progressBar = progressBar col = (progressLabel, statusLabel, estimateLabel, progressBar) if cancel: cancelButton = Button("Cancel", action=widget.cancel, fg_color=(255, 0, 0, 255)) col += (Column((cancelButton,), align="r"),) widget.add(Column(col)) widget.shrink_wrap() widget.startTime = datetime.now() if widget.present(): return widget.progressAmount else: return "Canceled"
11,659
30.945205
131
py
MCEdit-Unified
MCEdit-Unified-master/albow/grid_view.py
from pygame import Rect from widget import Widget class GridView(Widget): # cell_size (width, height) size of each cell # # Abstract methods: # # num_rows() --> no. of rows # num_cols() --> no. of columns # draw_cell(surface, row, col, rect) # click_cell(row, col, event) def __init__(self, cell_size, nrows, ncols, **kwds): """nrows, ncols are for calculating initial size of widget""" Widget.__init__(self, **kwds) self.cell_size = cell_size w, h = cell_size d = 2 * self.margin self.size = (w * ncols + d, h * nrows + d) self.cell_size = cell_size def draw(self, surface): for row in xrange(self.num_rows()): for col in xrange(self.num_cols()): r = self.cell_rect(row, col) self.draw_cell(surface, row, col, r) def cell_rect(self, row, col): w, h = self.cell_size d = self.margin x = col * w + d y = row * h + d return Rect(x, y, w, h) def draw_cell(self, surface, row, col, rect): pass def mouse_down(self, event): if event.button == 1: x, y = event.local w, h = self.cell_size W, H = self.size d = self.margin if d <= x < W - d and d <= y < H - d: row = (y - d) // h col = (x - d) // w self.click_cell(row, col, event) def click_cell(self, row, col, event): pass
1,533
27.943396
69
py
MCEdit-Unified
MCEdit-Unified-master/albow/file_opener.py
#-# This is not an albow component. #-# It should be moved back to MCEdit root folder, since it does not defines GUI base widgets. import os import logging import panels import pymclevel import albow import mcplatform from config import config from albow.translate import _ class FileOpener(albow.Widget): is_gl_container = True def __init__(self, mcedit, *args, **kwargs): kwargs['rect'] = mcedit.rect albow.Widget.__init__(self, *args, **kwargs) self.anchor = 'tlbr' self.mcedit = mcedit self.root = self.get_root() #-# Translation live update self.buildWidgets() def buildWidgets(self): for w in self.subwidgets: w.set_parent(None) helpColumn = [] self.root.movementLabel = label = albow.Label(_("{0}/{1}/{2}/{3}/{4}/{5} to move").format( _(config.keys.forward.get()), _(config.keys.left.get()), _(config.keys.back.get()), _(config.keys.right.get()), _(config.keys.up.get()), _(config.keys.down.get()), ), doNotTranslate=True) label.anchor = 'whrt' label.align = 'r' helpColumn.append(label) def addHelp(text, dnt=False): label = albow.Label(text, doNotTranslate=dnt) label.anchor = 'whrt' label.align = "r" helpColumn.append(label) return label self.root.slowDownLabel = addHelp(_("{0} to slow down").format(_(config.keys.brake.get())), dnt=True) self.camCont = addHelp("Right-click to toggle camera control") self.toolDist = addHelp("Mousewheel to control tool distance") self.root.detailsLabel = addHelp(_("Hold {0} for details").format(_(config.keys.showBlockInfo.get())), dnt=True) self.helpColumn = helpColumn = albow.Column(helpColumn, align="r") helpColumn.topright = self.topright helpColumn.anchor = "whrt" # helpColumn.is_gl_container = True self.add(helpColumn) keysColumn = [albow.Label("")] buttonsColumn = [panels.ControlPanel.getHeader()] shortnames = [] for world in self.mcedit.recentWorlds(): shortname = os.path.basename(world) try: if pymclevel.MCInfdevOldLevel.isLevel(world): lev = pymclevel.MCInfdevOldLevel(world, readonly=True) shortname = lev.LevelName if lev.LevelName != lev.displayName: shortname = u"{0} ({1})".format(lev.LevelName, lev.displayName) except Exception as e: logging.warning( 'Couldn\'t get name from recent world: {0!r}'.format(e)) if shortname == "level.dat": shortname = os.path.basename(os.path.dirname(world)) if len(shortname) > 40: shortname = shortname[:37] + "..." shortnames.append(shortname) hotkeys = ([(config.keys.newWorld.get(), 'Create New World', self.createNewWorld), (config.keys.quickLoad.get(), 'Quick Load', self.mcedit.editor.askLoadWorld), (config.keys.open.get(), 'Open...', self.promptOpenAndLoad)] + [ ('F{0}'.format(i + 1), shortnames[i], self.createLoadButtonHandler(world)) for i, world in enumerate(self.mcedit.recentWorlds())]) self.root.commandRow = commandRow = albow.HotkeyColumn(hotkeys, keysColumn, buttonsColumn, translateButtons=range(3)) commandRow.anchor = 'lrh' sideColumn1 = self.mcedit.makeSideColumn1() sideColumn1.anchor = 'wh' spaceLabel = albow.Label("") spaceLabel.anchor = 'wh' sideColumn2 = self.mcedit.makeSideColumn2() sideColumn2.anchor = 'wh' contentRow = albow.Row((commandRow, albow.Column((sideColumn1, spaceLabel, sideColumn2)))) contentRow.center = self.center contentRow.anchor = "rh" self.contentRow = contentRow self.add(contentRow) self.invalidate() # self.shrink_wrap() def set_update_ui(self, v): albow.Widget.set_update_ui(self, v) if v: self.buildWidgets() #-# def gl_draw_self(self, root, offset): self.mcedit.editor.drawStars() def idleevent(self): self.mcedit.editor.doWorkUnit(onMenu=True) def key_down(self, evt): keyname = self.root.getKey(evt) if keyname == 'Alt-F4': raise SystemExit if keyname in ('F1', 'F2', 'F3', 'F4', 'F5'): self.mcedit.loadRecentWorldNumber(int(keyname[1])) if keyname == config.keys.quickLoad.get(): self.mcedit.editor.askLoadWorld() if keyname == config.keys.newWorld.get(): self.createNewWorld() if keyname == config.keys.open.get(): self.promptOpenAndLoad() if keyname == config.keys.quit.get(): self.mcedit.confirm_quit() self.root.fix_sticky_ctrl() def promptOpenAndLoad(self): #!# Bad! But used to test the file chooser. # try: filename = mcplatform.askOpenFile(schematics=True) if filename: self.mcedit.loadFile(filename) # except Exception, e: # logging.error('Error during proptOpenAndLoad: {0!r}'.format(e)) def createNewWorld(self): self.parent.createNewWorld() def createLoadButtonHandler(self, filename): return lambda: self.mcedit.loadFile(filename)
5,561
35.352941
125
py
MCEdit-Unified
MCEdit-Unified-master/albow/tab_panel.py
# ############################################################### # # Albow - Tab Panel # ################################################################ #-# Modified by D.C.-G. for translation purpose from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from albow import * from pygame import Rect, Surface, image from pygame.locals import SRCALPHA from widget import Widget from theme import ThemeProperty, FontProperty from utils import brighten from numpy import fromstring from translate import _ # useless? class TabPanel(Widget): # pages [Widget] # current_page Widget tab_font = FontProperty('tab_font') tab_height = ThemeProperty('tab_height') tab_border_width = ThemeProperty('tab_border_width') tab_spacing = ThemeProperty('tab_spacing') tab_margin = ThemeProperty('tab_margin') tab_fg_color = ThemeProperty('tab_fg_color') default_tab_bg_color = ThemeProperty('default_tab_bg_color') tab_area_bg_color = ThemeProperty('tab_area_bg_color') tab_dimming = ThemeProperty('tab_dimming') tab_titles = None #use_page_bg_color_for_tabs = ThemeProperty('use_page_bg_color_for_tabs') def __init__(self, pages=None, **kwds): Widget.__init__(self, **kwds) self.pages = [] self.current_page = None if pages: w = h = 0 for title, page in pages: w = max(w, page.width) h = max(h, page.height) self._add_page(title, page) self.size = (w, h) self.show_page(pages[0][1]) def content_size(self): return self.width, self.height - self.tab_height def content_rect(self): return Rect((0, self.tab_height), self.content_size()) def page_height(self): return self.height - self.tab_height def add_page(self, title, page, idx=None): self._add_page(title, page, idx) if not self.current_page: self.show_page(page) def _add_page(self, title, page, idx=None): page.tab_title = _(title) page.anchor = 'ltrb' if idx is not None: self.pages.insert(idx, page) else: self.pages.append(page) def remove_page(self, page): try: i = self.pages.index(page) del self.pages[i] except IndexError: pass if page is self.current_page: self.show_page(None) def show_page(self, page): if self.current_page: self.remove(self.current_page) self.current_page = page if page: th = self.tab_height page.rect = Rect(0, th, self.width, self.height - th) self.add(page) page.focus() def draw(self, surf): self.draw_tab_area_bg(surf) self.draw_tabs(surf) def draw_tab_area_bg(self, surf): bg = self.tab_area_bg_color if bg: surf.fill(bg, (0, 0, self.width, self.tab_height)) def draw_tabs(self, surf): font = self.tab_font fg = self.tab_fg_color b = self.tab_border_width if b: surf.fill(fg, (0, self.tab_height - b, self.width, b)) for i, title, page, selected, rect in self.iter_tabs(): x0 = rect.left w = rect.width h = rect.height r = rect if not selected: r = Rect(r) r.bottom -= b self.draw_tab_bg(surf, page, selected, r) if b: surf.fill(fg, (x0, 0, b, h)) surf.fill(fg, (x0 + b, 0, w - 2 * b, b)) surf.fill(fg, (x0 + w - b, 0, b, h)) buf = font.render(title, True, page.fg_color or fg) r = buf.get_rect() r.center = (x0 + w // 2, h // 2) surf.blit(buf, r) def iter_tabs(self): pages = self.pages current_page = self.current_page n = len(pages) b = self.tab_border_width s = self.tab_spacing h = self.tab_height m = self.tab_margin width = self.width - 2 * m + s - b x0 = m for i, page in enumerate(pages): x1 = m + (i + 1) * width // n # self.tab_boundary(i + 1) selected = page is current_page yield i, page.tab_title, page, selected, Rect(x0, 0, x1 - x0 - s + b, h) x0 = x1 def draw_tab_bg(self, surf, page, selected, rect): bg = self.tab_bg_color_for_page(page) if not selected: bg = brighten(bg, self.tab_dimming) surf.fill(bg, rect) def tab_bg_color_for_page(self, page): return getattr(page, 'tab_bg_color', None) \ or page.bg_color \ or self.default_tab_bg_color def mouse_down(self, e): x, y = e.local if y < self.tab_height: i = self.tab_number_containing_x(x) if i is not None: if self.current_page: self.current_page.dispatch_attention_loss() self.show_page(self.pages[i]) def tab_number_containing_x(self, x): n = len(self.pages) m = self.tab_margin width = self.width - 2 * m + self.tab_spacing - self.tab_border_width i = (x - m) * n // width if 0 <= i < n: return i def gl_draw_self(self, root, offset): self.gl_draw(root, offset) def gl_draw(self, root, offset): pages = self.pages if len(pages) > 1: tlcorner = (offset[0] + self.bottomleft[0], offset[1] + self.bottomleft[1]) current_page = self.current_page n = len(pages) b = self.tab_border_width s = self.tab_spacing h = self.tab_height m = self.tab_margin tabWidth = (self.size[0] - (s * n) - (2 * m)) / n x0 = m + tlcorner[0] font = self.tab_font fg = self.tab_fg_color surface = Surface(self.size, SRCALPHA) glEnable(GL_BLEND) for i, page in enumerate(pages): x1 = x0 + tabWidth selected = page is current_page if selected: glColor(1.0, 1.0, 1.0, 0.5) else: glColor(0.5, 0.5, 0.5, 0.5) glRectf(x0, tlcorner[1] - (m + b), x1, tlcorner[1] - h) buf = font.render(self.pages[i].tab_title, True, self.fg_color or fg) r = buf.get_rect() offs = ((tabWidth - r.size[0]) / 2) + m + ((s + tabWidth) * i) surface.blit(buf, (offs, m)) x0 = x1 + s data = image.tostring(surface, 'RGBA', 1) rect = self.rect.move(offset) w, h = root.size glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(0, w, 0, h) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glRasterPos2i(rect.left, h - rect.bottom) glPushAttrib(GL_COLOR_BUFFER_BIT) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glDrawPixels(self.width, self.height, GL_RGBA, GL_UNSIGNED_BYTE, fromstring(data, dtype='uint8')) glPopAttrib() glFlush() glDisable(GL_BLEND)
7,406
31.92
87
py
MCEdit-Unified
MCEdit-Unified-master/albow/menu_bar.py
# # Albow - Menu bar # from pygame import Rect from widget import Widget, overridable_property class MenuBar(Widget): menus = overridable_property('menus', "List of Menu instances") def __init__(self, menus=None, width=0, **kwds): font = self.predict_font(kwds) height = font.get_linesize() Widget.__init__(self, Rect(0, 0, width, height), **kwds) self.menus = menus or [] self._hilited_menu = None def get_menus(self): return self._menus def set_menus(self, x): self._menus = x def draw(self, surf): fg = self.fg_color bg = self.bg_color font = self.font hilited = self._hilited_menu x = 0 for menu in self._menus: text = " %s " % menu.title if menu is hilited: buf = font.render(text, True, bg, fg) else: buf = font.render(text, True, fg, bg) surf.blit(buf, (x, 0)) x += surf.get_width() def mouse_down(self, e): mx = e.local[0] font = self.font x = 0 for menu in self._menus: text = " %s " % menu.title w = font.size(text)[0] if x <= mx < x + w: self.show_menu(menu, x) def show_menu(self, menu, x): self._hilited_menu = menu try: i = menu.present(self, (x, self.height)) finally: self._hilited_menu = None menu.invoke_item(i) def handle_command_key(self, e): menus = self.menus for m in xrange(len(menus) - 1, -1, -1): menu = menus[m] i = menu.find_item_for_key(e) if i >= 0: menu.invoke_item(i) return True return False
1,795
25.80597
67
py
MCEdit-Unified
MCEdit-Unified-master/albow/vectors.py
try: from Numeric import add, subtract, maximum except ImportError: import operator def add(x, y): return map(operator.add, x, y) def subtract(x, y): return map(operator.sub, x, y) def maximum(*args): result = args[0] for x in args[1:]: result = map(max, result, x) return result
358
16.95
46
py
MCEdit-Unified
MCEdit-Unified-master/albow/translate.py
# -*- encoding: utf_8 -*- # # /usr/bin/python # # translate.py # # (c) D.C.-G. 2014 # # Translation module for Python 2.7, especialy for Albow 2 and MCEdit 1.8 799 # #------------------------------------------------------------------------------- """This module adds translation functionnalities to Albow. It looks for locale files in a sub folder 'lang' according to the system default, or user specified locale. The locale files are text files where 'entries' are defined. Syntax example: o0 This is the first entry. t0 Ceci est la première entrée. o1 Here is the second one. You can see it is splitted on two lines. t1 Voici la deuxième. Vous pouvez constater qu'elle est sur deux lignes. The 'oN' markers on the begining of a line marks the original string; the 'tN', the translations. Strings can be splited on several lines and contain any sort of characters (thus, be aware of unicode). Files are named according to their language name, e.g. fr_FR.trn for french. The extension .trn is an arbitrary convention. The file 'template.trn' is given to be used as a base for other ones. It contains the strings used in Albow. They are not translated. As convention, english is considered as the default language, and the file en_EN.trn would never be present. Usage: You need, a least, these three function in your program: * setLangPath to define the translations location; * buildTranslation to build up the cache; * _ function to translate strings. """ import logging log = logging.getLogger(__name__) import os import re import codecs import json import resource import directories import platform, locale def getPlatInfo(**kwargs): """kwargs: dict: {"module_name": module,...} used to display version information about modules.""" log.debug("*** Platform information") log.debug(" System: %s" % platform.system()) log.debug(" Release: %s" % platform.release()) log.debug(" Version: %s" % platform.version()) log.debug(" Architecture: %s, %s" % platform.architecture()) log.debug(" Dist: %s, %s, %s" % platform.dist()) log.debug(" Machine: %s" % platform.machine()) log.debug(" Processor: %s" % platform.processor()) log.debug(" Locale: %s" % locale.getdefaultlocale()[0]) log.debug(" Encoding: %s" % locale.getdefaultlocale()[1]) log.debug(" FS encoding: %s" % os.sys.getfilesystemencoding()) reVer = re.compile(r"__version__|_version_|__version|_version|version|" "__ver__|_ver_|__ver|_ver|ver", re.IGNORECASE) for name, mod in kwargs.items(): s = "%s" % dir(mod) verObjNames = list(re.findall(reVer, s)) if len(verObjNames) > 0: while verObjNames: verObjName = verObjNames.pop() verObj = getattr(mod, verObjName, None) if verObj: if isinstance(verObj, (str, unicode, int, list, tuple)): ver = "%s" % verObj break elif "%s" % type(verObj) == "<type 'module'>": # There is no define module type, so this should stay verObjNames += ["%s.%s" % (verObjName, a) for a in re.findall(reVer, "%s" % dir(verObj))] else: ver = verObj() else: ver = "%s" % type(verObj) log.debug(" %s version: %s" % (name, ver)) log.debug("***") enc = locale.getdefaultlocale()[1] if enc is None: enc = "UTF-8" string_cache = {} font_lang_cache = {} #langPath = directories.getDataDir("lang") langPath = directories.getDataFile("lang") lang = "Default" # template building strNum = 0 template = {} # {"string": number} buildTemplate = False trnHeader = """# TRANSLATION BASICS # # This file works by mapping original English strings(o##) to the new translated strings(t##) # As long as the numbers match, it will translate the specified English string to the new language. # Any text formatting is preserved, so new lines, tabs, spaces, brackets, quotes and other special characters can be used. # # The space (' ') separating the strings from the numbers is mandatory. # The file must also be encoded in UTF-8 or it won't work. Most editors should support this. # # See TRANSLATION.txt for more detailed information. #""" buildTemplateMarker = """ ### THE FOLLOWING LINES HAS BEEN ADDED BY THE TEMPLATE UPDATE FUNCTION. ### Please, consider to analyze them and remove the entries referring ### to ones containing string formatting. ### ### For example, if you have a line already defined with this text: ### My %{animal} has %d legs. ### you may find lines like these below: ### My parrot has 2 legs. ### My dog has 4 legs. ### ### And, remove this paragraph too... """ #------------------------------------------------------------------------------- # Translation loading and mapping functions #------------------------------------------------------------------------------- def _(string, doNotTranslate=False, hotKey=False): """Returns the translated 'string', or 'string' itself if no translation found.""" if isinstance(string, str): string = unicode(string, enc) if doNotTranslate: return string if not isinstance(string, (str, unicode)): return string trn = string_cache.get(string, string) if trn == string and '-' in string: # Support for hotkeys trn = '-'.join([_(a, hotKey=True) for a in string.split('-') if _(a, hotKey=True) != a or a]) hotKey = True # We don't want hotkeys and blank strings. if buildTemplate and not hotKey and string.strip(): global template global strNum if (string, None) not in [(a, None) for a, b in template.values()]: template[len(template.keys())] = (string, "") strNum += 1 return trn or string #------------------------------------------------------------------------------- def loadTemplate(fName="template.trn"): """Load the template fName file in the global template variable. Returns the template.""" global template global trnHeader global strNum fName = os.path.join(getLangPath(), fName) if os.access(fName, os.F_OK) and os.path.isfile(fName) and os.access(fName, os.R_OK): oldData = codecs.open(fName, "r", "utf-8").read() + buildTemplateMarker trnHeader = u"" # find the first oXX start = re.search(ur"^o\d+[ ]", oldData, re.M|re.S) if start: start = start.start() else: print "*** %s malformed. Could not find entry point.\n Template not loaded."%os.path.split(fName)[-1] trnHeader += oldData[:max(0, start - 1)] trnPattern = re.compile(ur"^o\d+[ ]|^t\d+[ ]", re.M|re.S) grps = re.finditer(trnPattern, oldData) oStart = -1 oEnd = -1 tStart = -1 tEnd = -1 org = None num = 0 oNum = -1 tNum = -1 for grp in grps: g = grp.group() if g.startswith(u"o"): oStart = grp.end() tEnd = grp.start() - 1 oNum = int(g[1:]) elif g.startswith(u"t"): oEnd = grp.start() - 1 tStart = grp.end() tNum = int(g[1:]) if oNum == tNum: org = oldData[oStart:oEnd] if tStart > -1 and (tEnd > -1): if tEnd >= tStart: template[num] = (org, oldData[tStart:tEnd]) num += 1 tStart = -1 tEnd = -1 template[num] = (org, oldData[tStart:tEnd]) strNum = num return template #------------------------------------------------------------------------------- def saveTemplate(): if buildTemplate: fName = os.path.abspath(os.path.join(getLangPath(), "template.trn")) f = codecs.open(fName, "w", "utf-8") f.write(trnHeader) keys = template.keys() keys.sort() for key in keys: org, trn = template[key] f.write(u"\no%s %s\nt%s %s" % (key, org, key, trn)) f.close() #------------------------------------------------------------------------------- def setLangPath(path): """Changes the default 'lang' folder path. Retrun True if the path is valid, False otherwise.""" log.debug("setLangPath <<<") log.debug("Argument 'path': %s" % path) path = os.path.normpath(os.path.abspath(path)) log.debug(" Norm and abs: %s" % path) log.debug("os.access(path, os.F_OK): %s; os.path.isdir(path): %s; os.access(path, os.R_OK): %s" % (os.access(path, os.F_OK), os.path.isdir(path), os.access(path, os.R_OK))) if os.access(path, os.F_OK) and os.path.isdir(path) and os.access(path, os.R_OK): log.debug("'path' is valid") global langPath langPath = path return True log.debug("'path' is not valid") log.debug("setLangPath >>>") return False #------------------------------------------------------------------------------- def getLangPath(): """Return the actual 'lang' folder.""" return langPath #------------------------------------------------------------------------------- def getLang(): """Return the actual language.""" return lang def setLang(newlang): """Set the actual language. Returns old and new languages and string_cache in a tulpe. newlang: str: new laguage to load in the format <language>_<country>""" global lang oldLang = "" + lang if not lang == newlang: sc, result = buildTranslation(newlang) lang = newlang if newlang == 'en_US': result = True try: resource.setCurLang(u"English (US)") except: resource.__curLang = u"English (US)" else: result = True return oldLang, lang, result #------------------------------------------------------------------------------- def correctEncoding(data, oldEnc="ascii", newEnc=enc): """Returns encoded/decoded data. Disabled for now...""" return data # disabled for now, but can be use full in the future if type(data) == str: data = data.decode(newEnc) elif type(data) == unicode: data = data.encode(oldEnc) if "\n" in data: data = data.replace("\n", "\n\n") return data #------------------------------------------------------------------------------- def getLangName(file, path=None): """Return the language name defined in the .trn file. If the name is not found, return the file base name.""" if not path: path = langPath f = codecs.open(os.path.join(path, file), "r", "utf-8") line = f.readline() if "#-# " in line: name = line.split("#-# ")[1].strip() else: name = os.path.splitext(os.path.basename(file))[0] line = f.readline() regular = None if "#-# font regular: " in line: regular = line.split("#-# font regular: ")[1].strip() line = f.readline() bold = None if "#-# font bold: " in line: bold = line.split("#-# font bold: ")[1].strip() global font_lang_cache if regular and regular.lower() != "default": if not font_lang_cache.get("DejaVuSans-Regular.ttf", False): font_lang_cache["DejaVuSans-Regular.ttf"] = {name: regular} else: font_lang_cache["DejaVuSans-Regular.ttf"][name] = regular if bold and bold.lower() != "default": if not font_lang_cache.get("DejaVuSans-Bold.ttf", False): font_lang_cache["DejaVuSans-Bold.ttf"] = {name: bold} else: font_lang_cache["DejaVuSans-Bold.ttf"][name] = bold resource.font_lang_cache = font_lang_cache return name from time import time #------------------------------------------------------------------------------- def buildTranslation(lang, extend=False, langPath=None): """Finds the file corresponding to 'lang' builds up string_cache. If the file is not valid, does nothing. Errors encountered during the process are silently ignored. Returns string_cache (dict) and wether the file exists (bool).""" log.debug("buildTranslation <<<") tm = time() if not langPath: langPath = getLangPath() #str_cache = {} global string_cache fileFound = False lang = u"%s" % lang fName = os.path.join(langPath, lang + ".trn") log.debug("fName: %s" % fName) if os.access(fName, os.F_OK) and os.path.isfile(fName) and os.access(fName, os.R_OK): fileFound = True rawData = codecs.open(fName, "r", "utf-8").read() log.debug("fName is valid and read.") log.debug("Type of file data is %s"%("%s"%type(rawData)).strip("<type '").strip(">")[:-1]) log.debug("Parsing file and building JSON resource.") log.debug(" * Start on %s"%tm) start = re.search(r"^o\d+[ ]", rawData, re.M|re.S) if start: start = start.start() else: log.warning(" *** %s malformed. Could not find entry point.\n Translation not loaded.") # exiting without further operations return {}, False data = rawData[start:] trnPattern = re.compile(r"^o\d+[ ]|^t\d+[ ]", re.M|re.S) grps = re.findall(trnPattern, data) if len(grps) % 2 != 0: grps1 = re.findall(r"^o\d+[ ]", data, re.M|re.S) grps2 = re.findall(r"^t\d+[ ]", data, re.M|re.S) log.warning(" Unpaired original and translated strings. %s is longer (oXX: %s, tXX: %s)."%({True: "tXX", False: "oXX"}[len(grps1) < len(grps2)], len(grps1), len(grps2))) bugStrs = [] def compLists(lst1, lst1N, lst2, lst2N, repl, bugStrs=bugStrs): bug = [] for item in lst1: itm = repl + item[1:] if itm in lst2: idx = lst2.index(itm) lst2.pop(idx) else: bug.append(item) bugStrs += ["Not found in %s"%lst1N, bug] bugStrs += ["Not found in %s"%lst2N, lst2] if len(grps1) < len(grps2): compLists(grps1, "grps1", grps2, "grps2", u"t") log.warning(" Compared oXX tXX:") log.warning(" %s"%bugStrs) else: compLists(grps2, "grps2", grps1, "grps1", u"o") log.warning(" Compared tXX oXX:") log.warning(" %s"%bugStrs) return {}, False n1 = len(grps) / 2 result = u"" n = 1 n2 = 0 r = u"" + data.replace(u"\\", u"\\\\").replace(u"\"", u'\\"').replace(u"\r\n", u"\n").replace(u"\r", u"\n") log.debug(" Replacing oXX/tXX.") while n: r, n = re.subn(r"^o\d+[ ]|\no\d+[ ]", "\",\"", r, flags=re.M|re.S) r, n = re.subn(r"^t\d+[ ]|\nt\d+[ ]", "\":\"", r, flags=re.M|re.S) n2 += n if n2 == n1: n = 0 log.debug(" Replaced %s occurences."%n2) result += r[2:] result = u"{" + result.replace(u"\r\n", u"\\n").replace(u"\n", u"\\n").replace(u"\t", u"\\t") + u"\"}" log.debug(" Conversion done. Loading JSON resource.") try: str_cache = json.loads(result) if extend: string_cache.update([(a, b) for (a, b) in str_cache.items() if a not in string_cache.keys()]) except Exception as e: log.debug("Error while loading JSON resource:") log.debug(" %s"%e) log.debug("Dumping JSON data in %s.json"%lang) f = open('%s.json'%lang, 'w') f.write(result) f.close() return {}, False # log.debug(" Setting up font.") # Forgotten this here??? if not extend: line = rawData.splitlines()[0] if "#-# " in line: lngNm = line.split("#-# ")[1].strip() else: lngNm = os.path.splitext(os.path.basename(fName))[0] try: resource.setCurLang(lngNm) except: resource.__curLang = lngNm tm1 = time() log.debug(" * End on %s duration %s"%(tm, tm1 - tm)) else: log.debug("fName is not valid beacause:") if not os.access(fName, os.F_OK): log.debug(" * Can't access file.") if not os.path.isfile(fName): log.debug(" * It's not a file.") if not os.access(fName, os.R_OK): log.debug(" * Is not readable.") log.debug("Default strings will be used.") str_cache = {} if not extend: string_cache = str_cache log.debug("buildTranslation >>>") return string_cache, fileFound #------------------------------------------------------------------------------- if __name__ == "__main__": ### FOR TEST import sys for k, v in buildTranslation("template").items(): print k, v sys.exit() ###
17,130
35.84086
184
py
MCEdit-Unified
MCEdit-Unified-master/albow/utils.py
from pygame import Surface from pygame.locals import SRCALPHA def frame_rect(surface, color, rect, thick=1): o = 1 surface.fill(color, (rect.left + o, rect.top, rect.width - o - o, thick)) surface.fill(color, (rect.left + o, rect.bottom - thick, rect.width - o - o, thick)) surface.fill(color, (rect.left, rect.top + o, thick, rect.height - o - o)) surface.fill(color, (rect.right - thick, rect.top + o, thick, rect.height - o - o)) def blit_tinted(surface, image, pos, tint, src_rect=None): from Numeric import add, minimum from pygame.surfarray import array3d, pixels3d if src_rect: image = image.subsurface(src_rect) buf = Surface(image.get_size(), SRCALPHA, 32) buf.blit(image, (0, 0)) src_rgb = array3d(image) buf_rgb = pixels3d(buf) buf_rgb[...] = minimum(255, add(tint, src_rgb)).astype('b') surface.blit(buf, pos) def blit_in_rect(dst, src, frame, align='tl', margin=0): r = src.get_rect() align_rect(r, frame, align, margin) dst.blit(src, r) def align_rect(r, frame, align='tl', margin=0): if 'l' in align: r.left = frame.left + margin elif 'r' in align: r.right = frame.right - margin else: r.centerx = frame.centerx if 't' in align: r.top = frame.top + margin elif 'b' in align: r.bottom = frame.bottom - margin else: r.centery = frame.centery def brighten(rgb, factor): return [min(255, int(round(factor * c))) for c in rgb]
1,500
29.02
88
py
MCEdit-Unified
MCEdit-Unified-master/albow/image_array.py
from pygame import Rect from albow.resource import get_image class ImageArray(object): def __init__(self, image, shape): self.image = image self.shape = shape if isinstance(shape, tuple): self.nrows, self.ncols = shape else: self.nrows = 1 self.ncols = shape iwidth, iheight = image.get_size() self.size = iwidth // self.ncols, iheight // self.nrows def __len__(self): return self.shape def __getitem__(self, index): image = self.image nrows = self.nrows if nrows == 1: row = 0 col = index else: row, col = index # left = iwidth * col // ncols #top = iheight * row // nrows #width = iwidth // ncols #height = iheight // nrows width, height = self.size left = width * col top = height * row return image.subsurface(left, top, width, height) def get_rect(self): return Rect((0, 0), self.size) image_array_cache = {} def get_image_array(name, shape, **kwds): result = image_array_cache.get(name) if not result: result = ImageArray(get_image(name, **kwds), shape) image_array_cache[name] = result return result
1,292
24.86
63
py
MCEdit-Unified
MCEdit-Unified-master/albow/layout.py
# # Albow - Layout widgets # from pygame import Rect from widget import Widget class RowOrColumn(Widget): _is_gl_container = True focusable = False def __init__(self, size, items, kwds): align = kwds.pop('align', 'c') self.spacing = spacing = kwds.pop('spacing', 10) expand = kwds.pop('expand', None) if isinstance(expand, int): expand = items[expand] #-# Translation live update preparation self.expand = expand self.align = align self._size = size #-# #if kwds: # raise TypeError("Unexpected keyword arguments to Row or Column: %s" # % kwds.keys()) Widget.__init__(self, **kwds) #-# Translation live update preparation self.calc_size(items) def calc_size(self, _items=None): if _items: items = _items else: items = self.subwidgets expand = self.expand align = self.align size = self._size spacing = self.spacing #-# # If the 'expand' value is in 'h' or 'v', resize the widgets according # to the larger one. if type(expand) in (str, unicode): w = 'n' h = 'n' if 'h' in expand: # Expand horizontally w = max([a.width for a in items]) if 'v' in expand: # Expand vertically h = max([a.height for a in items]) if w != 'n' and h == 'n': for item in items: item.width = w elif w == 'n' and h != 'n': for item in items: item.height = h elif w != 'n' and h != 'n': for item in items: item.width = w item.height = h d = self.d longways = self.longways crossways = self.crossways axis = self.axis k, attr2, attr3 = self.align_map[align] w = 0 length = 0 if items: if isinstance(expand, int): expand = items[expand] elif not expand: expand = items[-1] move = '' for item in items: r = item.rect w = max(w, getattr(r, crossways)) if item is expand: item.set_resizing(axis, 's') move = 'm' else: item.set_resizing(axis, move) length += getattr(r, longways) if size is not None: n = len(items) if n > 1: length += spacing * (n - 1) setattr(expand.rect, longways, max(1, size - length)) h = w * k // 2 m = self.margin px = h * d[1] + m py = h * d[0] + m sx = spacing * d[0] sy = spacing * d[1] for item in items: setattr(item.rect, attr2, (px, py)) #-# Translation live update preparation if _items: self.add(item) #-# p = getattr(item.rect, attr3) px = p[0] + sx py = p[1] + sy self.shrink_wrap() def call_handler(self, name, *args): # Automatically call the parent *_action methods if Widget.call_handler(self, name, *args) == 'pass': return self.call_parent_handler(name, *args) #--------------------------------------------------------------------------- class Row(RowOrColumn): d = (1, 0) axis = 'h' longways = 'width' crossways = 'height' align_map = { 't': (0, 'topleft', 'topright'), 'c': (1, 'midleft', 'midright'), 'b': (2, 'bottomleft', 'bottomright'), } def __init__(self, items, width=None, **kwds): """ Row(items, align=alignment, spacing=10, width=None, expand=None) align = 't', 'c' or 'b' """ RowOrColumn.__init__(self, width, items, kwds) #--------------------------------------------------------------------------- class Column(RowOrColumn): d = (0, 1) axis = 'v' longways = 'height' crossways = 'width' align_map = { 'l': (0, 'topleft', 'bottomleft'), 'c': (1, 'midtop', 'midbottom'), 'r': (2, 'topright', 'bottomright'), } def __init__(self, items, height=None, **kwds): """ Column(items, align=alignment, spacing=10, height=None, expand=None) align = 'l', 'c' or 'r' """ RowOrColumn.__init__(self, height, items, kwds) #--------------------------------------------------------------------------- class Grid(Widget): _is_gl_container = True def __init__(self, rows, row_spacing=10, column_spacing=10, **kwds): col_widths = [0] * len(rows[0]) row_heights = [0] * len(rows) for j, row in enumerate(rows): for i, widget in enumerate(row): if widget: col_widths[i] = max(col_widths[i], widget.width) row_heights[j] = max(row_heights[j], widget.height) row_top = 0 for j, row in enumerate(rows): h = row_heights[j] y = row_top + h // 2 col_left = 0 for i, widget in enumerate(row): if widget: w = col_widths[i] x = col_left widget.midleft = (x, y) col_left += w + column_spacing row_top += h + row_spacing width = max(1, col_left - column_spacing) height = max(1, row_top - row_spacing) r = Rect(0, 0, width, height) #print "albow.controls.Grid: r =", r ### #print "...col_widths =", col_widths ### #print "...row_heights =", row_heights ### Widget.__init__(self, r, **kwds) self.add(rows) #--------------------------------------------------------------------------- class Frame(Widget): # margin int spacing between border and widget border_width = 1 margin = 2 def __init__(self, client, border_spacing=None, **kwds): Widget.__init__(self, **kwds) self.client = client if border_spacing is not None: self.margin = self.border_width + border_spacing d = self.margin w, h = client.size self.size = (w + 2 * d, h + 2 * d) client.topleft = (d, d) self.add(client) def call_handler(self, name, *args): # Automatically call the parent *_action methods if Widget.call_handler(self, name, *args) == 'pass': return self.call_parent_handler(name, *args)
6,663
29.429224
80
py
MCEdit-Unified
MCEdit-Unified-master/albow/menu.py
# --------------------------------------------------------------------------- # # Albow - Pull-down or pop-up menu # #--------------------------------------------------------------------------- #-# Modified by D.C.-G. for translation purpose import sys from root import get_root, get_focus from dialogs import Dialog from theme import ThemeProperty from pygame import Rect, draw from translate import _ #--------------------------------------------------------------------------- class MenuItem(object): keyname = "" keycode = None shift = False alt = False enabled = False if sys.platform.startswith('darwin') or sys.platform.startswith('mac'): cmd_name = "Cmd " option_name = "Opt " else: cmd_name = "Ctrl " option_name = "Alt " def __init__(self, text="", command=None, doNotTranslate=False): self.command = command if "/" in text: text, key = text.split("/", 1) else: key = "" self.text = _(text, doNotTranslate=doNotTranslate) if key: keyname = key[-1] mods = key[:-1] self.keycode = ord(keyname.lower()) if "^" in mods: self.shift = True keyname = "Shift " + keyname if "@" in mods: self.alt = True keyname = self.option_name + keyname self.keyname = self.cmd_name + keyname #--------------------------------------------------------------------------- class Menu(Dialog): disabled_color = ThemeProperty('disabled_color') click_outside_response = -1 scroll_button_size = ThemeProperty('scroll_button_size') scroll_button_color = ThemeProperty('scroll_button_color') scroll = 0 def __init__(self, title, items, scrolling=False, scroll_items=30, scroll_page=5, handler=None, **kwds): self.handler = handler self.title = _(title, doNotTranslate=kwds.get('doNotTranslate', False)) self.items = items self._items = [MenuItem(*item, doNotTranslate=kwds.get('doNotTranslate', False)) for item in items] self.scrolling = scrolling and len(self._items) > scroll_items self.scroll_items = scroll_items self.scroll_page = scroll_page self._selected_item_index = 0 self._hilited = self._items[self._selected_item_index] Dialog.__init__(self, **kwds) self.root = self.get_root() self.calc_size() #&# def set_items(self, items): self.items = items self._items = [MenuItem(*item, doNotTranslate=self.doNotTranslate) for item in items] def set_scroll_items(self, scroll_items): if scroll_items < len(self.items): self.scroll_items = scroll_items else: self.scroll_items = len(self.items) self.calc_size() #&# def calc_size(self): h = self.font.get_linesize() if self.scrolling: self.height = h * self.scroll_items + h else: self.height = h * len(self._items) + h def set_update_ui(self, v): if v: self._items = [MenuItem(*item, doNotTranslate=self.doNotTranslate) for item in self.items] Dialog.set_update_ui(self, v) def present(self, client, pos): client = client or self.root self.topleft = client.local_to_global(pos) focus = self.handler or get_focus() font = self.font h = font.get_linesize() items = self._items margin = self.margin if self.scrolling: height = h * self.scroll_items + h else: height = h * len(items) + h w1 = w2 = 0 for item in items: item.enabled = self.command_is_enabled(item, focus) w1 = max(w1, font.size(item.text)[0]) w2 = max(w2, font.size(item.keyname)[0]) width = w1 + 2 * margin self._key_margin = width if w2 > 0: width += w2 + margin if self.scrolling: width += self.scroll_button_size self.size = (width, height) self._hilited = None self.rect.clamp_ip(self.root.rect) return Dialog.present(self, centered=False) @staticmethod def command_is_enabled(item, focus): cmd = item.command if cmd: enabler_name = cmd + '_enabled' handler = focus while handler: enabler = getattr(handler, enabler_name, None) if enabler: return enabler() handler = handler.next_handler() return True def scroll_up_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.top = m r.right = self.width - m r.inflate_ip(-4, -4) return r def scroll_down_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.bottom = self.height - m r.right = self.width - m r.inflate_ip(-4, -4) return r def draw(self, surf): font = self.font h = font.get_linesize() sep = surf.get_rect() sep.height = 1 if self.scrolling: sep.width -= self.margin + self.scroll_button_size colors = [self.disabled_color, self.fg_color] bg = self.bg_color xt = self.margin xk = self._key_margin y = h // 2 hilited = self._hilited if self.scrolling: items = self._items[self.scroll:self.scroll + self.scroll_items] else: items = self._items for item in items: text = item.text if not text: sep.top = y + h // 2 surf.fill(colors[0], sep) else: if item is hilited: rect = surf.get_rect() rect.top = y rect.height = h if self.scrolling: rect.width -= xt + self.scroll_button_size surf.fill(colors[1], rect) color = bg else: color = colors[item.enabled] buf = font.render(item.text, True, color) surf.blit(buf, (xt, y)) keyname = item.keyname if keyname: buf = font.render(keyname, True, color) surf.blit(buf, (xk, y)) y += h if self.scrolling: if self.can_scroll_up(): self.draw_scroll_up_button(surf) if self.can_scroll_down(): self.draw_scroll_down_button(surf) def draw_scroll_up_button(self, surface): r = self.scroll_up_rect() c = self.scroll_button_color draw.polygon(surface, c, [r.bottomleft, r.midtop, r.bottomright]) def draw_scroll_down_button(self, surface): r = self.scroll_down_rect() c = self.scroll_button_color draw.polygon(surface, c, [r.topleft, r.midbottom, r.topright]) def mouse_move(self, e): self.mouse_drag(e) def mouse_drag(self, e): item = self.find_enabled_item(e) if item is not self._hilited: self._hilited = item self.invalidate() if item: self._selected_item_index = self._items.index(item) def mouse_up(self, e): if 1 <= e.button <= 3: item = self.find_enabled_item(e) if item: self.dismiss(self._items.index(item)) def find_enabled_item(self, e): x, y = e.local if 0 <= x < (self.width - self.margin - self.scroll_button_size if self.scrolling else self.width): h = self.font.get_linesize() i = (y - h // 2) // h + self.scroll items = self._items if 0 <= i < len(items): item = items[i] if item.enabled: return item def mouse_down(self, event): if event.button == 1: if self.scrolling: p = event.local if self.scroll_up_rect().collidepoint(p): self.scroll_up() return elif self.scroll_down_rect().collidepoint(p): self.scroll_down() return if event.button == 4: self.scroll_up() if event.button == 5: self.scroll_down() Dialog.mouse_down(self, event) def scroll_up(self): if self.can_scroll_up(): self.scroll = max(self.scroll - self.scroll_page, 0) def scroll_down(self): if self.can_scroll_down(): self.scroll = min(self.scroll + self.scroll_page, len(self._items) - self.scroll_items) def can_scroll_up(self): return self.scrolling and self.scroll > 0 def can_scroll_down(self): return (self.scrolling and self.scroll + self.scroll_items < len(self._items)) def find_item_for_key(self, e): for item in self._items: if item.keycode == e.key \ and item.shift == e.shift and item.alt == e.alt: focus = get_focus() if self.command_is_enabled(item, focus): return self._items.index(item) else: return -1 return -1 def get_command(self, i): if i >= 0: item = self._items[i] cmd = item.command if cmd: return cmd + '_cmd' def invoke_item(self, i): cmd = self.get_command(i) if cmd: get_focus().handle_command(cmd) def key_down(self, event): """Handles key presses to select and activate menu items or dismiss it. :param event: object: The event to be processed.""" key = self.root.getKey(event) last_index = len(self._items) - 1 # Just define a dummy method when scrolling is not necessary. def _x(*args, **kwargs): """...""" pass def page_up_down(*args, **kwargs): """Triggers scroll alignment to see the selected item on page up/down event.""" self.scroll = min(self._selected_item_index, last_index - self.scroll_items + 1) view_meth = _x if key == "Up": if self._selected_item_index == 0: self._selected_item_index = last_index self.scroll = last_index - self.scroll_items + 1 else: self._selected_item_index -= 1 view_meth = self.scroll_up elif key == "Down": if self._selected_item_index == last_index: self._selected_item_index = 0 self.scroll = 0 else: self._selected_item_index += 1 view_meth = self.scroll_down elif key == "Page up": self._selected_item_index = max(0, self._selected_item_index - self.scroll_items) view_meth = page_up_down elif key == "Page down": self._selected_item_index = min(last_index, self._selected_item_index + self.scroll_items) view_meth = page_up_down elif key in ("Return", "Enter", "Space"): self.dismiss(self._selected_item_index) elif key == "Escape": self.dismiss(False) else: Dialog.key_down(self, event) self._hilited = self._items[self._selected_item_index] # Ensure the selected item is visible by scrollign accordingly if self._hilited not in self._items[self.scroll:self.scroll + self.scroll_items]: view_meth()
11,860
32.600567
107
py
MCEdit-Unified
MCEdit-Unified-master/albow/shell.py
# # Albow - Shell # from root import RootWidget #------------------------------------------------------------------------------ class Shell(RootWidget): def __init__(self, surface, **kwds): RootWidget.__init__(self, surface, **kwds) self.current_screen = None def show_screen(self, new_screen): old_screen = self.current_screen if old_screen is not new_screen: if old_screen: old_screen.leave_screen() self.remove(old_screen) self.add(new_screen) self.current_screen = new_screen if new_screen: new_screen.focus() new_screen.enter_screen() def begin_frame(self): screen = self.current_screen if screen: screen.begin_frame()
810
25.16129
79
py
MCEdit-Unified
MCEdit-Unified-master/albow/dialogs.py
#-# Modified by D.C.-G. for translation purpose import textwrap from pygame import event, key from pygame.locals import * from widget import Widget from controls import Label, Button from layout import Row, Column from fields import TextFieldWrapped from scrollpanel import ScrollPanel from table_view import TableView, TableColumn from translate import _ class Modal(object): enter_response = True cancel_response = False def ok(self): self.dismiss(True) def cancel(self): self.dismiss(False) class Dialog(Modal, Widget): click_outside_response = None def __init__(self, client=None, responses=None, default=0, cancel=-1, **kwds): Widget.__init__(self, **kwds) self.root = self.get_root() if client or responses: rows = [] w1 = 0 w2 = 0 if client: rows.append(client) w1 = client.width if responses: buttons = Row([ Button(text, action=lambda t=text: self.dismiss(t)) for text in responses]) rows.append(buttons) w2 = buttons.width if w1 < w2: a = 'l' else: a = 'r' contents = Column(rows, align=a) m = self.margin contents.topleft = (m, m) self.add(contents) self.shrink_wrap() if responses and default is not None: self.enter_response = responses[default] if responses and cancel is not None: self.cancel_response = responses[cancel] def mouse_down(self, e): if not e in self: response = self.click_outside_response if response is not None: self.dismiss(response) def key_down(self, e): pass def key_up(self, e): pass class QuickDialog(Dialog): """ Dialog that closes as soon as you click outside or press a key""" def mouse_down(self, evt): if evt not in self: self.dismiss(-1) if evt.button != 1: event.post(evt) def key_down(self, evt): self.dismiss() event.post(evt) def wrapped_label(text, wrap_width, **kwds): # paras = text.split("\n") text = _(text) kwds['doNotTranslate'] = True paras = text.split("\n") text = "\n".join([textwrap.fill(para, wrap_width) for para in paras]) return Label(text, **kwds) # def alert(mess, wrap_width = 60, **kwds): # box = Dialog(**kwds) # d = box.margin # lb = wrapped_label(mess, wrap_width) # lb.topleft = (d, d) # box.add(lb) # box.shrink_wrap() # return box.present() def alert(mess, **kwds): ask(mess, ["OK"], **kwds) ask_tied_to = None # ask_tied_to = [] ask_tied_tos = [] def ask(mess, responses=("OK", "Cancel"), default=0, cancel=-1, wrap_width=60, **kwds): # If height is specified as a keyword, the Dialog object will have this haight, and the inner massage will # be displayed in a scrolling widget # If 'responses_tooltips' it present in kwds, it must be dict with 'responses' as keys and the tooltips as values. # If 'tie_widget_to' is in kwds keys and the value is True, the global 'ask_tied_to' will be set up to the 'box'. # When called again with 'tie_widget_to', if 'ask_tied_to' is not None, the function returns a dummy answer. global ask_tied_to responses_tooltips = kwds.pop('responses_tooltips', {}) tie_widget_to = kwds.pop('tie_widget_to', None) # Return a dummy answer if tie_windget_to is True and the global 'ask_tied_to' is not None if tie_widget_to and ask_tied_to: return "_OK" colLbl = kwds.pop('colLabel', "") box = Dialog(**kwds) d = box.margin lb = wrapped_label(mess, wrap_width) buts = [] for caption in responses: but = Button(caption, action=lambda x=caption: box.dismiss(x)) if caption in responses_tooltips.keys(): but.tooltipText = responses_tooltips[caption] buts.append(but) brow = Row(buts, spacing=d) lb.width = max(lb.width, brow.width) height = kwds.get('height', None) if height and lb.height > height - (2 * brow.height) - ScrollPanel.column_margin - box.margin: lines = mess.split('\n') # ScrolledPanel refuses to render properly for now, so Tableview is used instead. w = TableView().font.size(_(colLbl))[0] lb = TableView(columns=[TableColumn(colLbl, max(lb.width, w)),], nrows=(height - (2 * brow.height) - box.margin - box.font.get_linesize()) / box.font.get_linesize(), height=height - (2 * brow.height) - (box.font.get_linesize() * 2) - box.margin) #, width=w) def num_rows(): return len(lines) lb.num_rows = num_rows lb.row_data = lambda x: (lines[x],) lb.topleft = (d, d) lb.width = max(lb.width, brow.width) col = Column([lb, brow], spacing=d, align='r') col.topleft = (d, d) if default is not None: box.enter_response = responses[default] buts[default].is_default = True else: box.enter_response = None if cancel is not None: box.cancel_response = responses[cancel] else: box.cancel_response = None box.add(col) box.shrink_wrap() def dispatchKeyForAsk(name, evt): if name == "key_down" and box.root.getKey(evt) == "Return" and default is not None: box.dismiss(responses[default]) else: Dialog.dispatch_key(box, name, evt) box.dispatch_key = dispatchKeyForAsk if tie_widget_to: ask_tied_to = box ask_tied_tos.append(box) return box.present() def input_text(prompt, width, initial=None, **kwds): box = Dialog(**kwds) d = box.margin def ok(): box.dismiss(True) def cancel(): box.dismiss(False) lb = Label(prompt) lb.topleft = (d, d) tf = TextFieldWrapped(width) if initial: tf.set_text(initial) tf.enter_action = ok tf.escape_action = cancel tf.top = lb.top tf.left = lb.right + 5 box.add(lb) box.add(tf) tf.focus() box.shrink_wrap() if box.present(): return tf.get_text() else: return None def input_text_buttons(prompt, width, initial=None, allowed_chars=None, **kwds): box = Dialog(**kwds) d = box.margin def ok(): box.dismiss(True) def cancel(): box.dismiss(False) buts = [Button("OK", action=ok), Button("Cancel", action=cancel)] brow = Row(buts, spacing=d) lb = Label(prompt) lb.topleft = (d, d) tf = TextFieldWrapped(width,allowed_chars=allowed_chars) if initial: tf.set_text(initial) tf.enter_action = ok tf.escape_action = cancel tf.top = lb.top tf.left = lb.right + 5 trow = Row([lb, tf], spacing=d) col = Column([trow, brow], spacing=d, align='c') col.topleft = (d, d) box.add(col) tf.focus() box.shrink_wrap() if box.present(): return tf.get_text() else: return None
7,136
27.894737
265
py
MCEdit-Unified
MCEdit-Unified-master/albow/version.py
version = (2, 1, 0)
20
9.5
19
py
MCEdit-Unified
MCEdit-Unified-master/albow/scrollpanel.py
# -*- coding: utf_8 -*- # # scrollpanel.py # # Scrollable widget which contains other widgets, for albow # from palette_view import PaletteView from layout import Column from utils import blit_in_rect from pygame import event, Surface, SRCALPHA, Rect, draw, mouse #----------------------------------------------------------------------------- class ScrollRow(PaletteView): __tooltipText = None @property def tooltipText(self): pos = mouse.get_pos() x, y = self.global_to_local(pos) # print "pos", pos # print "x", x, "y", y w, h = self.cell_size W, H = self.size d = self.margin if d <= x < W - d and d <= y < H - d: row = (y - d) // h if row < self.num_items(): row_data = self.row_data(row) if isinstance(row_data, list): return self.row_data(row)[-1] else: return self.__tooltipText @tooltipText.setter def tooltipText(self, text): self.__tooltipText = text def __init__(self, cell_size, nrows, **kwargs): self.draw_zebra = kwargs.pop('draw_zebra', True) scrolling = kwargs.pop('scrolling', True) self.hscrolling = kwargs.pop('hscrolling', True) self.hscroll = 0 self.virtual_width = 1000 self.dragging_hhover = False self.hscroll_rel = 0 PaletteView.__init__(self, cell_size, nrows, 1, scrolling=scrolling) if self.hscrolling: self.height += self.scroll_button_size def draw_item(self, surf, row, row_rect): if self.hscrolling: if row_rect.bottom > self.scroll_left_rect().top: return row_data = self.row_data(row) table = self.parent height = row_rect.height for i, x, width, column, cell_data in table.column_info(row_data): cell_rect = Rect(x + self.margin - self.hscroll, row_rect.top, width, height) self.draw_table_cell(surf, row, cell_data, cell_rect, column) def draw_item_and_highlight(self, surface, i, rect, highlight): if self.draw_zebra and i % 2: surface.fill(self.zebra_color, rect) if highlight: self.draw_prehighlight(surface, i, rect) if highlight and self.highlight_style == 'reverse': fg = self.inherited('bg_color') or self.sel_color else: fg = self.fg_color self.draw_item_with(surface, i, rect, fg) if highlight: self.draw_posthighlight(surface, i, rect) def draw_table_cell(self, surf, i, data, cell_rect, column): self.parent.draw_tree_cell(surf, i, data, cell_rect, column) def item_is_selected(self, n): return n == self.parent.selected_item_index def num_items(self): return self.parent.num_rows() def num_rows(self): return max(0, PaletteView.num_rows(self) - 1) def row_data(self, row): return self.parent.row_data(row) def click_item(self, n, e): self.parent.click_item(n, e) def scroll_up_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.top = m r.right = self.width - m r.inflate_ip(-4, -4) return r def scroll_down_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.right = self.width - m if self.hscrolling: m += d r.bottom = self.height - m r.inflate_ip(-4, -4) return r def scroll_left_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.bottom = self.height - m r.left = m r.inflate_ip(-4, -4) return r def scroll_right_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.bottom = self.height - m if self.scrolling: m += d r.right = self.width - m r.inflate_ip(-4, -4) return r def hscrollbar_rect(self): # Get the distance between the scroll buttons (d) slr, slt = self.scroll_left_rect().topright d = self.scroll_right_rect().left - slr # The predefined step value _s = self.cell_size[1] # Get the total step number n = float(self.virtual_width) / _s # Get the visible step number v = float(self.width) / _s s = float(d) / n w = s * v if isinstance(w, float): if w - int(w) > 0: w += 1 left = max(slr, slr + (d * (float(self.hscroll) / self.virtual_width)) + self.hscroll_rel) r = Rect(left, slt, w, self.scroll_button_size) r.right = min(r.right, d + slr) r.inflate_ip(-4, -4) if r.w < 1: r.w = int(w) return r def can_scroll_left(self): return self.hscrolling and self.hscroll > 0 def can_scroll_right(self): return self.hscrolling and self.hscroll + self.width < self.virtual_width def draw_scroll_left_button(self, surface): r = self.scroll_left_rect() c = self.scroll_button_color draw.polygon(surface, c, [r.midleft, r.topright, r.bottomright]) def draw_scroll_right_button(self, surface): r = self.scroll_right_rect() c = self.scroll_button_color draw.polygon(surface, c, [r.topleft, r.midright, r.bottomleft]) def draw_hscrollbar(self, surface): r = self.hscrollbar_rect() c = map(lambda x: min(255, max(0, x + 10)), self.scroll_button_color) draw.rect(surface, c, r) def draw(self, surface): for row in xrange(self.num_rows()): for col in xrange(self.num_cols()): r = self.cell_rect(row, col) self.draw_cell(surface, row, col, r) u = False d = False l = False r = False if self.can_scroll_up(): u = True self.draw_scroll_up_button(surface) if self.can_scroll_down(): d = True self.draw_scroll_down_button(surface) if self.can_scroll_left(): l = True self.draw_scroll_left_button(surface) if self.can_scroll_right(): r = True self.draw_scroll_right_button(surface) if u or d: self.draw_scrollbar(surface) if l or r: self.draw_hscrollbar(surface) def scroll_left(self, delta=1): if self.can_scroll_left(): self.hscroll -= self.cell_size[1] * delta def scroll_right(self, delta=1): if self.can_scroll_right(): self.hscroll += self.cell_size[1] * delta def mouse_down(self, event): if event.button == 1: if self.hscrolling: p = event.local if self.hscrollbar_rect().collidepoint(p): self.dragging_hhover = True return elif self.scroll_left_rect().collidepoint(p): self.scroll_left() return elif self.scroll_right_rect().collidepoint(p): self.scroll_right() return elif event.button == 6: if self.hscrolling: self.scroll_left() elif event.button == 7: if self.hscrolling: self.scroll_right() PaletteView.mouse_down(self, event) def mouse_drag(self, event): if self.dragging_hhover: self.hscroll_rel += event.rel[0] slr, slt = self.scroll_left_rect().topright d = self.scroll_right_rect().left - slr _s = self.cell_size[1] n = float(self.virtual_width) / _s s = float(d) / n if abs(self.hscroll_rel) > s: if self.hscroll_rel > 0: self.scroll_right(delta=int(abs(self.hscroll_rel) / s)) else: self.scroll_left(delta=int(abs(self.hscroll_rel) / s)) self.hscroll_rel = 0 PaletteView.mouse_drag(self, event) def mouse_up(self, event): if self.dragging_hhover: self.dragging_hhover = False self.hscroll_rel = 0 PaletteView.mouse_up(self, event) def cell_rect(self, row, col): w, h = self.cell_size d = self.margin x = col * w + d - self.hscroll y = row * h + d return Rect(x, y, w, h) #----------------------------------------------------------------------------- class ScrollPanel(Column): column_margin = 2 def __init__(self, *args, **kwargs): kwargs['margin'] = kwargs.get('margin', 0) self.selected_item_index = None self.rows = kwargs.pop('rows', []) self.align = kwargs.get('align', 'l') self.spacing = kwargs.get('spacing', 4) self.draw_zebra = kwargs.pop('draw_zebra', True) # self.row_height = kwargs.pop('row_height', max([a.height for a in self.rows] + [self.font.size(' ')[1],])) self.row_height = kwargs.pop('row_height', max([a.height for a in self.rows] + [self.font.get_linesize(),])) self.inner_width = kwargs.pop('inner_width', 500) self.scrolling = kwargs.get('scrolling', True) self.hscrolling = kwargs.get('hscrolling', True) self.scrollRow = scrollRow = ScrollRow((self.inner_width, self.row_height), 10, draw_zebra=self.draw_zebra, spacing=0, scrolling=self.scrolling, hscrolling=self.hscrolling) self.selected = None Column.__init__(self, [scrollRow,], **kwargs) self.shrink_wrap() def draw_tree_cell(self, surf, i, data, cell_rect, column): """...""" if self.align.lower() == 'r': cell_rect.right = self.right - self.margin if self.scrollRow.can_scroll_up() or self.scrollRow.can_scroll_down(): cell_rect.right -= self.scrollRow.scroll_button_size elif self.align.lower() == 'c': cell_rect.left = self.centerx - (cell_rect.width / 2) if isinstance(data, (str, unicode)): self.draw_text_cell(surf, i, data, cell_rect, self.align, self.font) else: self.draw_image_cell(surf, i, data, cell_rect, column) def draw_image_cell(self, surf, i, data, cell_rect, column): """...""" blit_in_rect(surf, data, cell_rect, self.align, self.margin) def draw_text_cell(self, surf, i, data, cell_rect, align, font): buf = font.render(unicode(data), True, self.fg_color) blit_in_rect(surf, buf, cell_rect, align) def num_rows(self): return len(self.rows) def row_data(self, row): return self.rows[row] def column_info(self, row_data): m = self.column_margin d = 2 * m x = 0 width = 0 subs = row_data.subwidgets for i in xrange(len(subs)): sub = subs[i] width += sub.width surf = Surface((sub.width, sub.height), SRCALPHA) sub.draw_all(surf) yield i, x + m, sub.width - d, i, surf x += width def click_item(self, n, e): if n < len(self.rows): for sub in self.rows[n].subwidgets: if sub: x = e.local[0] - self.margin - self.rows[n].rect.left - self.rows[n].margin - self.scrollRow.cell_rect(n, 0).left - sub.rect.left y = e.local[1] - self.margin - self.rows[n].rect.top - self.rows[n].margin - self.scrollRow.cell_rect(n, 0).top - sub.rect.top if sub.left <= x <= sub.right: _e = event.Event(e.type, {'alt': e.alt, 'meta': e.meta, 'ctrl': e.ctrl, 'shift': e.shift, 'button': e.button, 'cmd': e.cmd, 'num_clicks': e.num_clicks, 'local': (x, y), 'pos': e.local}) self.focus_on(sub) if self.selected: self.selected.is_modal = False sub.is_modal = True sub.mouse_down(_e) self.selected = sub break
12,344
34.886628
175
py
MCEdit-Unified
MCEdit-Unified-master/albow/music.py
# --------------------------------------------------------------------------- # # Albow - Music # #--------------------------------------------------------------------------- from __future__ import division import os from random import randrange try: from pygame.mixer import music except ImportError: music = None print "Music not available" if music: import root music.set_endevent(root.MUSIC_END_EVENT) from resource import resource_path from root import schedule #--------------------------------------------------------------------------- fadeout_time = 1 # Time over which to fade out music (sec) change_delay = 2 # Delay between end of one item and starting the next (sec) #--------------------------------------------------------------------------- music_enabled = True current_music = None current_playlist = None next_change_delay = 0 #--------------------------------------------------------------------------- class PlayList(object): """A collection of music filenames to be played sequentially or randomly. If random is true, items will be played in a random order. If repeat is true, the list will be repeated indefinitely, otherwise each item will only be played once.""" def __init__(self, items, random=False, repeat=False): self.items = list(items) self.random = random self.repeat = repeat def next(self): """Returns the next item to be played.""" items = self.items if items: if self.random: n = len(items) if self.repeat: n = (n + 1) // 2 i = randrange(n) else: i = 0 item = items.pop(i) if self.repeat: items.append(item) return item #--------------------------------------------------------------------------- def get_music(*names, **kwds): """Return the full pathname of a music file from the "music" resource subdirectory.""" prefix = kwds.pop('prefix', "music") return resource_path(prefix, *names) def get_playlist(*names, **kwds): prefix = kwds.pop('prefix', "music") dirpath = get_music(*names, **{'prefix': prefix}) items = [os.path.join(dirpath, filename) for filename in os.listdir(dirpath) if not filename.startswith(".")] items.sort() return PlayList(items, **kwds) def change_playlist(new_playlist): """Fade out any currently playing music and start playing from the given playlist.""" #print "albow.music: change_playlist" ### global current_music, current_playlist, next_change_delay if music and new_playlist is not current_playlist: current_playlist = new_playlist if music_enabled: music.fadeout(fadeout_time * 1000) next_change_delay = max(0, change_delay - fadeout_time) jog_music() else: current_music = None def change_music(new_music, repeat=False): """Fade out any currently playing music and start playing the given music file.""" #print "albow.music: change_music" ### if music and new_music is not current_music: if new_music: new_playlist = PlayList([new_music], repeat=repeat) else: new_playlist = None change_playlist(new_playlist) def music_end(): #print "albow.music: music_end" ### schedule(next_change_delay, jog_music) def jog_music(): """If no music is currently playing, start playing the next item from the current playlist.""" if music_enabled and not music.get_busy(): start_next_music() def start_next_music(): """Start playing the next item from the current playlist immediately.""" #print "albow.music: start_next_music" ### global current_music, next_change_delay if music_enabled and current_playlist: next_music = current_playlist.next() if next_music: print "albow.music: loading", repr(next_music) ### music.load(next_music) music.play() next_change_delay = change_delay current_music = next_music def get_music_enabled(): return music_enabled def set_music_enabled(state): global music_enabled if music_enabled != state: music_enabled = state if state: # Music pausing doesn't always seem to work. #music.unpause() if current_music: # After stopping and restarting currently loaded music, # fadeout no longer works. #print "albow.music: reloading", repr(current_music) ### music.load(current_music) music.play() else: jog_music() else: #music.pause() music.stop() #--------------------------------------------------------------------------- from pygame import Rect from albow.widget import Widget from albow.controls import Label, Button, CheckBox from albow.layout import Row, Column, Grid from albow.dialogs import Dialog class EnableMusicControl(CheckBox): def get_value(self): return get_music_enabled() def set_value(self, x): set_music_enabled(x) class MusicVolumeControl(Widget): def __init__(self, **kwds): Widget.__init__(self, Rect((0, 0), (100, 20)), **kwds) def draw(self, surf): r = self.get_margin_rect() r.width = int(round(music.get_volume() * r.width)) surf.fill(self.fg_color, r) def mouse_down(self, e): self.mouse_drag(e) def mouse_drag(self, e): m = self.margin w = self.width - 2 * m x = max(0.0, min(1.0, (e.local[0] - m) / w)) music.set_volume(x) self.invalidate() class MusicOptionsDialog(Dialog): def __init__(self): Dialog.__init__(self) emc = EnableMusicControl() mvc = MusicVolumeControl() controls = Grid([ [Label("Enable Music"), emc], [Label("Music Volume"), mvc], ]) buttons = Button("OK", self.ok) contents = Column([controls, buttons], align='r', spacing=20) contents.topleft = (20, 20) self.add(contents) self.shrink_wrap() def show_music_options_dialog(): dlog = MusicOptionsDialog() dlog.present()
6,386
28.031818
77
py
MCEdit-Unified
MCEdit-Unified-master/albow/root.py
# --------------------------------------------------------------------------- # # Albow - Root widget # #--------------------------------------------------------------------------- import sys import traceback import pygame from pygame import key from pygame.locals import * from pygame.event import Event from glbackground import * import widget from widget import Widget from datetime import datetime, timedelta from albow.dialogs import wrapped_label from albow.translate import _ from pymclevel.box import Vector # -# This need to be changed. We need albow.translate in the config module. # -# he solution can be a set of functions wich let us define the needed MCEdit 'config' data # -# without importing it. # -# It can be a 'config' module built only for albow. from config import config # -# import os import directories import time from dialogs import Dialog, Label, Button, Row, Column from OpenGL import GL start_time = datetime.now() mod_cmd = KMOD_LCTRL | KMOD_RCTRL | KMOD_LMETA | KMOD_RMETA double_click_time = timedelta(0, 0, 300000) # days, seconds, microseconds import logging log = logging.getLogger(__name__) modifiers = dict( shift=False, ctrl=False, alt=False, meta=False, ) modkeys = { K_LSHIFT: 'shift', K_RSHIFT: 'shift', K_LCTRL: 'ctrl', K_RCTRL: 'ctrl', K_LALT: 'alt', K_RALT: 'alt', K_LMETA: 'meta', K_RMETA: 'meta', } MUSIC_END_EVENT = USEREVENT + 1 last_mouse_event = Event(0, pos=(0, 0), local=(0, 0)) last_mouse_event_handler = None root_widget = None # Root of the containment hierarchy top_widget = None # Initial dispatch target clicked_widget = None # Target of mouse_drag and mouse_up events #--------------------------------------------------------------------------- class Cancel(Exception): pass #--------------------------------------------------------------------------- def set_modifier(modifier_key, value): attr = modkeys.get(modifier_key) if attr: modifiers[attr] = value def add_modifiers(event): d = event.dict d.update(modifiers) d['cmd'] = event.ctrl or event.meta def get_root(): return root_widget def get_top_widget(): return top_widget def get_focus(): return top_widget.get_focus() #--------------------------------------------------------------------------- class RootWidget(Widget): # surface Pygame display surface # is_gl True if OpenGL surface redraw_every_frame = False bonus_draw_time = False _is_gl_container = True def __init__(self, surface): global root_widget Widget.__init__(self, surface.get_rect()) self.surface = surface root_widget = self widget.root_widget = self self.is_gl = surface.get_flags() & OPENGL != 0 self.idle_handlers = [] self.editor = None self.selectTool = None self.movementMath = [-1, 1, 1, -1, 1, -1] self.movementNum = [0, 0, 2, 2, 1, 1] self.cameraMath = [-1., 1., -1., 1.] self.cameraNum = [0, 0, 1, 1] self.notMove = False self.nudge = None self.testTime = None self.testTimeBack = 0.4 self.nudgeDirection = None self.sessionStolen = False self.sprint = False self.filesToChange = [] def get_modifiers(self): """Returns the 'modifiers' global object.""" return modifiers def get_nudge_block(self): return self.selectTool.panel.nudgeBlocksButton def take_screenshot(self): try: os.mkdir(os.path.join(directories.getCacheDir(), "screenshots")) except OSError: pass screenshot_name = os.path.join(directories.getCacheDir(), "screenshots", time.strftime("%Y-%m-%d (%I-%M-%S-%p)") + ".png") pygame.image.save(pygame.display.get_surface(), screenshot_name) self.diag = Dialog() lbl = Label(_("Screenshot taken and saved as '%s'") % screenshot_name, doNotTranslate=True) folderBtn = Button("Open Folder", action=self.open_screenshots_folder) btn = Button("Ok", action=self.screenshot_notify) buttonsRow = Row((btn, folderBtn)) col = Column((lbl, buttonsRow)) self.diag.add(col) self.diag.shrink_wrap() self.diag.present() def open_screenshots_folder(self): from mcplatform import platform_open platform_open(os.path.join(directories.getCacheDir(), "screenshots")) self.screenshot_notify() def screenshot_notify(self): self.diag.dismiss() @staticmethod def set_timer(ms): pygame.time.set_timer(USEREVENT, ms) def run(self): self.run_modal(None) captured_widget = None def capture_mouse(self, widget): # put the mouse in "virtual mode" and pass mouse moved events to the # specified widget if widget: pygame.mouse.set_visible(False) pygame.event.set_grab(True) self.captured_widget = widget else: pygame.mouse.set_visible(True) pygame.event.set_grab(False) self.captured_widget = None frames = 0 hover_widget = None def fix_sticky_ctrl(self): self.ctrlClicked = -1 def run_modal(self, modal_widget): if self.editor is None: self.editor = self.mcedit.editor self.selectTool = self.editor.toolbar.tools[0] old_captured_widget = None if self.captured_widget: old_captured_widget = self.captured_widget self.capture_mouse(None) global last_mouse_event, last_mouse_event_handler global top_widget, clicked_widget is_modal = modal_widget is not None modal_widget = modal_widget or self #from OpenGL import GL try: old_top_widget = top_widget top_widget = modal_widget was_modal = modal_widget.is_modal modal_widget.is_modal = True modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() if clicked_widget: clicked_widget = modal_widget num_clicks = 0 last_click_time = start_time last_click_button = False self.bonus_draw_time = False while modal_widget.modal_result is None: try: if not self.mcedit.version_checked: if not self.mcedit.version_lock.locked(): self.mcedit.version_checked = True self.mcedit.check_for_version() self.hover_widget = self.find_widget(pygame.mouse.get_pos()) if not self.bonus_draw_time: self.bonus_draw_time = True if self.is_gl: self.gl_clear() self.gl_draw_all(self, (0, 0)) GL.glFlush() else: self.draw_all(self.surface) pygame.display.flip() self.frames += 1 events = pygame.event.get() if not events: self.call_idle_handlers() for event in events: type = event.type if type == QUIT: self.quit() elif type == MOUSEBUTTONDOWN: self.bonus_draw_time = False t = datetime.now() if t - last_click_time <= double_click_time and event.button == last_click_button: num_clicks += 1 else: num_clicks = 1 last_click_button = event.button last_click_time = t event.dict['num_clicks'] = num_clicks add_modifiers(event) mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget clicked_widget = mouse_widget last_mouse_event_handler = mouse_widget last_mouse_event = event mouse_widget.notify_attention_loss() mouse_widget.handle_mouse('mouse_down', event) elif type == MOUSEMOTION: self.bonus_draw_time = False add_modifiers(event) modal_widget.dispatch_key('mouse_delta', event) last_mouse_event = event mouse_widget = self.update_tooltip(event.pos) if clicked_widget: last_mouse_event_handler = clicked_widget clicked_widget.handle_mouse('mouse_drag', event) else: if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget last_mouse_event_handler = mouse_widget mouse_widget.handle_mouse('mouse_move', event) elif type == MOUSEBUTTONUP: add_modifiers(event) self.bonus_draw_time = False mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if clicked_widget: last_mouse_event_handler = clicked_widget event.dict['clicked_widget'] = clicked_widget else: last_mouse_event_handler = mouse_widget event.dict['clicked_widget'] = None last_mouse_event = event clicked_widget = None last_mouse_event_handler.handle_mouse('mouse_up', event) elif type == KEYDOWN: key_down = event.key set_modifier(key_down, True) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.takeAScreenshot.get(): self.take_screenshot() self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == KEYUP: key_up = event.key set_modifier(key_up, False) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.showBlockInfo.get() and self.editor.toolbar.tools[0].infoKey == 1: self.editor.toolbar.tools[0].infoKey = 0 self.editor.mainViewport.showCommands() if self.nudgeDirection is not None: keyname = self.getKey(movement=True, keyname=key.name(key_up)) for i, move_key in enumerate(self.editor.movements): if keyname == move_key and i == self.nudgeDirection: self.nudgeDirection = None self.testTime = None self.testTimeBack = 0.4 self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == MUSIC_END_EVENT: self.music_end() elif type == USEREVENT: make_scheduled_calls() if not is_modal: if self.redraw_every_frame: self.bonus_draw_time = False else: self.bonus_draw_time = True if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local add_modifiers(event) last_mouse_event_handler.setup_cursor(event) self.begin_frame() elif type == VIDEORESIZE: self.bonus_draw_time = False self.size = (event.w, event.h) elif type == VIDEOEXPOSE: if self.mcedit.displayContext.win and self.mcedit.displayContext.win.get_state() == 1: x, y = config.settings.windowX.get(), config.settings.windowY.get() pos = self.mcedit.displayContext.win.get_position() if pos[0] != x: config.settings.windowX.set(pos[0]) if pos[1] != y: config.settings.windowY.set(pos[1]) elif type == ACTIVEEVENT: add_modifiers(event) self.dispatch_key('activeevent', event) if not self.sessionStolen: try: if self.editor.level is not None and hasattr(self.editor.level, "checkSessionLock"): self.editor.level.checkSessionLock() except Exception as e: log.warn(u"Error reading chunk (?): %s", e) traceback.print_exc() if not config.session.override.get(): self.sessionStolen = True else: self.editor.level.acquireSessionLock() if self.editor.level is not None: self.editor.cameraInputs = [0., 0., 0., 0., 0., 0.] self.editor.cameraPanKeys = [0., 0., 0., 0.] def useKeys(i): keyName = self.getKey(movement=True, keyname=key.name(i)) if keyName == self.editor.sprintKey: self.sprint = True if allKeys[K_LCTRL] or allKeys[K_RCTRL] or allKeys[K_RMETA] or allKeys[K_LMETA]: return if keyName in self.editor.movements: self.changeMovementKeys(self.editor.movements.index(keyName), keyName) if keyName in self.editor.cameraPan: self.changeCameraKeys(self.editor.cameraPan.index(keyName)) allKeys = key.get_pressed() for x in enumerate(allKeys): if x[1]: useKeys(x[0]) for edit in self.filesToChange: newTime = os.path.getmtime(edit.filename) if newTime > edit.timeChanged: edit.timeChanged = newTime edit.makeChanges() except Cancel: pass finally: modal_widget.is_modal = was_modal top_widget = old_top_widget if old_captured_widget: self.capture_mouse(old_captured_widget) clicked_widget = None @staticmethod def getKey(evt=None, movement=False, keyname=None): if keyname is None: keyname = key.name(evt.key) keyname = keyname.replace("right ", "").replace("left ", "").replace("Meta", "Ctrl").replace("Enter", "Return").replace("Delete", "Del") try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) except: pass if movement: return keyname newKeyname = "" if evt.shift and keyname != "Shift": newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl": newKeyname += "Ctrl-" if evt.alt and keyname != "Alt": newKeyname += "Alt-" keyname = newKeyname + keyname if newKeyname: return keyname if sys.platform == 'linux2': test_key = getattr(evt, 'scancode', None) tool_keys = [10, 11, 12, 13, 14, 15, 16, 17, 18] else: test_key = keyname tool_keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] if test_key in tool_keys: keyname = str(tool_keys.index(test_key) + 1) elif test_key == 19: keyname = '0' return keyname def changeMovementKeys(self, keyNum, keyname): if self.editor.level is not None and not self.notMove: self.editor.cameraInputs[self.movementNum[keyNum]] += self.movementMath[keyNum] elif self.notMove and self.nudge is not None and (self.testTime is None or datetime.now() - self.testTime >= timedelta(seconds=self.testTimeBack)): if self.testTimeBack > 0.1: self.testTimeBack -= 0.1 self.bonus_draw_time = False self.testTime = datetime.now() if keyname == self.editor.movements[4]: self.nudge.nudge(Vector(0, 1, 0)) if keyname == self.editor.movements[5]: self.nudge.nudge(Vector(0, -1, 0)) Z = self.editor.mainViewport.cameraVector absZ = map(abs, Z) if absZ[0] < absZ[2]: forward = (0, 0, (-1 if Z[2] < 0 else 1)) else: forward = ((-1 if Z[0] < 0 else 1), 0, 0) back = map(int.__neg__, forward) left = forward[2], forward[1], -forward[0] right = map(int.__neg__, left) if keyname == self.editor.movements[2]: self.nudge.nudge(Vector(*forward)) if keyname == self.editor.movements[3]: self.nudge.nudge(Vector(*back)) if keyname == self.editor.movements[0]: self.nudge.nudge(Vector(*left)) if keyname == self.editor.movements[1]: self.nudge.nudge(Vector(*right)) for i, move_key in enumerate(self.editor.movements): if move_key == keyname: self.nudgeDirection = i def changeCameraKeys(self, keyNum): if self.editor.level is not None and not self.notMove: self.editor.cameraPanKeys[self.cameraNum[keyNum]] = self.cameraMath[keyNum] def RemoveEditFiles(self): self.filesToChange = [] def call_idle_handlers(self): def call(ref): widget = ref() if widget: widget.idleevent() else: print "Idle ref died!" return bool(widget) self.idle_handlers = filter(call, self.idle_handlers) def add_idle_handler(self, widget): from weakref import ref self.idle_handlers.append(ref(widget)) def remove_idle_handler(self, widget): from weakref import ref self.idle_handlers.remove(ref(widget)) @staticmethod def send_key(widget, name, event): widget.dispatch_key(name, event) def begin_frame(self): pass def get_root(self): return self labelClass = lambda s, t: wrapped_label(t, 45) def show_tooltip(self, widget, pos): if hasattr(self, 'currentTooltip'): if self.currentTooltip is not None: self.remove(self.currentTooltip) self.currentTooltip = None def TextTooltip(text, name): tooltipBacking = Panel(name=name) tooltipBacking.bg_color = (0.0, 0.0, 0.0, 0.8) tooltipBacking.add(self.labelClass(text)) tooltipBacking.shrink_wrap() return tooltipBacking def showTip(tip): tip.topleft = pos tip.top += 20 if (tip.bottom > self.bottom) or hasattr(widget, 'tooltipsUp'): tip.bottomleft = pos tip.top -= 4 if tip.right > self.right: tip.right = pos[0] self.add(tip) self.currentTooltip = tip if widget.tooltip is not None: tip = widget.tooltip showTip(tip) else: ttext = widget.tooltipText if ttext is not None: tip = TextTooltip(ttext, 'Panel.%s' % (repr(widget))) showTip(tip) def update_tooltip(self, pos=None): if pos is None: pos = pygame.mouse.get_pos() if self.captured_widget: mouse_widget = self.captured_widget pos = mouse_widget.center else: mouse_widget = self.find_widget(pos) self.show_tooltip(mouse_widget, pos) return mouse_widget def has_focus(self): return True def quit(self): if self.confirm_quit(): self.capture_mouse(None) sys.exit(0) @staticmethod def confirm_quit(): return True @staticmethod def get_mouse_for(widget): last = last_mouse_event event = Event(0, last.dict) event.dict['local'] = widget.global_to_local(event.pos) add_modifiers(event) return event def gl_clear(self): #from OpenGL import GL bg = self.bg_color if bg: r = bg[0] / 255.0 g = bg[1] / 255.0 b = bg[2] / 255.0 GL.glClearColor(r, g, b, 0.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) @staticmethod def music_end(): import music music.music_end() # -# Used for debugging the resize stuff. # def resized(self, *args, **kwargs): # Widget.resized(self, *args, **kwargs) # print self.size #--------------------------------------------------------------------------- from bisect import insort scheduled_calls = [] def make_scheduled_calls(): sched = scheduled_calls t = time() while sched and sched[0][0] <= t: sched[0][1]() sched.pop(0) def schedule(delay, func): """Arrange for the given function to be called after the specified delay in seconds. Scheduled functions are called synchronously from the event loop, and only when the frame timer is running.""" t = time() + delay insort(scheduled_calls, (t, func))
24,040
36.100309
155
py
MCEdit-Unified
MCEdit-Unified-master/albow/openglwidgets.py
# ------------------------------------------------------------------------- # # Albow - OpenGL widgets # #------------------------------------------------------------------------- from __future__ import division from OpenGL import GL, GLU from widget import Widget class GLViewport(Widget): is_gl_container = True def gl_draw_self(self, root, offset): rect = self.rect.move(offset) # GL_CLIENT_ALL_ATTRIB_BITS is borked: defined as -1 but # glPushClientAttrib insists on an unsigned long. #GL.glPushClientAttrib(0xffffffff) #GL.glPushAttrib(GL.GL_ALL_ATTRIB_BITS) GL.glViewport(rect.left, root.height - rect.bottom, rect.width, rect.height) self.gl_draw_viewport() #GL.glPopAttrib() #GL.glPopClientAttrib() def gl_draw_viewport(self): self.setup_matrices() self.gl_draw() def setup_matrices(self): GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() self.setup_projection() GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() self.setup_modelview() def setup_projection(self): pass def setup_modelview(self): pass def gl_draw(self): pass def augment_mouse_event(self, event): Widget.augment_mouse_event(self, event) w, h = self.size viewport = numpy.array((0, 0, w, h), dtype='int32') self.setup_matrices() gf = GL.glGetDoublev pr_mat = gf(GL.GL_PROJECTION_MATRIX) mv_mat = gf(GL.GL_MODELVIEW_MATRIX) x, y = event.local y = h - y up = GLU.gluUnProject try: p0 = up(x, y, 0.0, mv_mat, pr_mat, viewport) p1 = up(x, y, 1.0, mv_mat, pr_mat, viewport) event.dict['ray'] = (p0, p1) except ValueError: # projection failed! pass import numpy #------------------------------------------------------------------------- class GLOrtho(GLViewport): def __init__(self, rect=None, xmin=-1, xmax=1, ymin=-1, ymax=1, near=-1, far=1, **kwds): GLViewport.__init__(self, rect, **kwds) self.xmin = xmin self.xmax = xmax self.ymin = ymin self.ymax = ymax self.near = near self.far = far def setup_projection(self): GL.glOrtho(self.xmin, self.xmax, self.ymin, self.ymax, self.near, self.far) class GLPixelOrtho(GLOrtho): def __init__(self, rect=None, near=-1, far=1, **kwds): GLOrtho.__init__(self, rect, near, far, **kwds) self.xmin = 0 self.ymin = 0 self.xmax = self.width self.ymax = self.height #------------------------------------------------------------------------- class GLPerspective(GLViewport): def __init__(self, rect=None, fovy=20, near=0.1, far=1000, **kwds): GLViewport.__init__(self, rect, **kwds) self.fovy = fovy self.near = near self.far = far def setup_projection(self): aspect = self.width / self.height GLU.gluPerspective(self.fovy, aspect, self.near, self.far)
3,169
27.558559
84
py
MCEdit-Unified
MCEdit-Unified-master/albow/sound.py
# # Albow - Sound utilities # import pygame from pygame import mixer def pause_sound(): try: mixer.pause() except pygame.error: pass def resume_sound(): try: mixer.unpause() except pygame.error: pass def stop_sound(): try: mixer.stop() except pygame.error: pass
341
11.214286
25
py
MCEdit-Unified
MCEdit-Unified-master/albow/widget.py
from __future__ import division import sys import albow # used for translation update from pygame import Rect, Surface, image from pygame.locals import K_RETURN, K_KP_ENTER, K_ESCAPE, K_TAB, KEYDOWN, SRCALPHA from pygame.mouse import set_cursor from pygame.cursors import arrow as arrow_cursor from pygame.transform import rotozoom from vectors import add, subtract from utils import frame_rect import theme from theme import ThemeProperty, FontProperty import resource from numpy import fromstring from OpenGL import GL, GLU debug_rect = False debug_tab = True root_widget = None current_cursor = None def overridable_property(name, doc=None): """Creates a property which calls methods get_xxx and set_xxx of the underlying object to get and set the property value, so that the property's behaviour may be easily overridden by subclasses.""" getter_name = intern('get_' + name) setter_name = intern('set_' + name) return property( lambda self: getattr(self, getter_name)(), lambda self, value: getattr(self, setter_name)(value), None, doc) def rect_property(name): def get(self): return getattr(self._rect, name) def set(self, value): r = self._rect old_size = r.size setattr(r, name, value) new_size = r.size if old_size != new_size: self._resized(old_size) return property(get, set) # noinspection PyPropertyAccess class Widget(object): # rect Rect bounds in parent's coordinates # parent Widget containing widget # subwidgets [Widget] contained widgets # focus_switch Widget subwidget to receive key events # fg_color color or None to inherit from parent # bg_color color to fill background, or None # visible boolean # border_width int width of border to draw around widget, or None # border_color color or None to use widget foreground color # tab_stop boolean stop on this widget when tabbing # anchor string of 'ltrb' font = FontProperty('font') fg_color = ThemeProperty('fg_color') bg_color = ThemeProperty('bg_color') bg_image = ThemeProperty('bg_image') scale_bg = ThemeProperty('scale_bg') border_width = ThemeProperty('border_width') border_color = ThemeProperty('border_color') sel_color = ThemeProperty('sel_color') margin = ThemeProperty('margin') menu_bar = overridable_property('menu_bar') is_gl_container = overridable_property('is_gl_container') tab_stop = False enter_response = None cancel_response = None anchor = 'ltwh' debug_resize = False _menubar = None _visible = True _is_gl_container = False redraw_every_event = True tooltip = None tooltipText = None doNotTranslate = False # 'name' is used to track widgets without parent name = 'Widget' # 'focusable' is used to know if a widget can have the focus. # Used to tell container widgets like Columns or Dialogs tofind the next focusable widget # in their children. focusable = True def __init__(self, rect=None, **kwds): if rect and not isinstance(rect, Rect): raise TypeError("Widget rect not a pygame.Rect") self._rect = Rect(rect or (0, 0, 100, 100)) #-# Translation live update preparation self.__lang = albow.translate.getLang() self.__update_translation = False self.shrink_wrapped = False #-# self.parent = None self.subwidgets = [] self.focus_switch = None self.is_modal = False self.set(**kwds) self.root = self.get_root() self.setup_spacings() def __repr__(self): return "{0} {1}, child of {2}".format(super(Widget, self).__repr__(), getattr(self, "text", "\b").encode('ascii', errors='backslashreplace'), self.parent) #-# Translation live update preparation @property def get_update_translation(self): return self.__update_translation def set_update_ui(self, v): if v: self.font = self.predict_font({}) for widget in self.subwidgets: widget.set_update_ui(v) if self.shrink_wrapped: self.shrink_wrap() if hasattr(self, 'calc_size'): self.calc_size() self.invalidate() self.__update_translation = v #-# def setup_spacings(self): def new_size(size): size = float(size * 1000) / float(100) size = int(size * resource.font_proportion / 1000) return size self.margin = new_size(self.margin) if hasattr(self, 'spacing'): self.spacing = new_size(self.spacing) def set(self, **kwds): for name, value in kwds.iteritems(): if not hasattr(self, name): raise TypeError("Unexpected keyword argument '%s'" % name) setattr(self, name, value) def get_rect(self): return self._rect def set_rect(self, x): old_size = self._rect.size self._rect = Rect(x) self._resized(old_size) resizing_axes = {'h': 'lr', 'v': 'tb'} resizing_values = {'': [0], 'm': [1], 's': [0, 1]} def set_resizing(self, axis, value): chars = self.resizing_axes[axis] anchor = self.anchor for c in chars: anchor = anchor.replace(c, '') for i in self.resizing_values[value]: anchor += chars[i] self.anchor = anchor + value def _resized(self, (old_width, old_height)): new_width, new_height = self._rect.size dw = new_width - old_width dh = new_height - old_height if dw or dh: self.resized(dw, dh) def resized(self, dw, dh): if self.debug_resize: print "Widget.resized:", self, "by", (dw, dh), "to", self.size for widget in self.subwidgets: widget.parent_resized(dw, dh) def parent_resized(self, dw, dh): debug_resize = self.debug_resize or getattr(self.parent, 'debug_resize', False) if debug_resize: print "Widget.parent_resized:", self, "by", (dw, dh) left, top, width, height = self._rect move = False resize = False anchor = self.anchor if dw: factors = [1, 1, 1] # left, width, right if 'r' in anchor: factors[2] = 0 if 'w' in anchor: factors[1] = 0 if 'l' in anchor: factors[0] = 0 if any(factors): resize = factors[1] move = factors[0] or factors[2] #print "lwr", factors left += factors[0] * dw / sum(factors) width += factors[1] * dw / sum(factors) #left = (left + width) + factors[2] * dw / sum(factors) - width if dh: factors = [1, 1, 1] # bottom, height, top if 't' in anchor: factors[2] = 0 if 'h' in anchor: factors[1] = 0 if 'b' in anchor: factors[0] = 0 if any(factors): resize = factors[1] move = factors[0] or factors[2] #print "bht", factors top += factors[2] * dh / sum(factors) height += factors[1] * dh / sum(factors) #top = (top + height) + factors[0] * dh / sum(factors) - height if resize: if debug_resize: print "Widget.parent_resized: changing rect to", (left, top, width, height) self.rect = Rect((left, top, width, height)) elif move: if debug_resize: print "Widget.parent_resized: moving to", (left, top) self._rect.topleft = (left, top) rect = property(get_rect, set_rect) left = rect_property('left') right = rect_property('right') top = rect_property('top') bottom = rect_property('bottom') width = rect_property('width') height = rect_property('height') size = rect_property('size') topleft = rect_property('topleft') topright = rect_property('topright') bottomleft = rect_property('bottomleft') bottomright = rect_property('bottomright') midleft = rect_property('midleft') midright = rect_property('midright') midtop = rect_property('midtop') midbottom = rect_property('midbottom') center = rect_property('center') centerx = rect_property('centerx') centery = rect_property('centery') def get_visible(self): return self._visible def set_visible(self, x): self._visible = x visible = overridable_property('visible') def add(self, arg, index=None): if arg: if isinstance(arg, Widget): if index is not None: arg.set_parent(self, index) else: arg.set_parent(self) else: for item in arg: self.add(item) def add_centered(self, widget): w, h = self.size widget.center = w // 2, h // 2 self.add(widget) def remove(self, widget): if widget in self.subwidgets: widget.set_parent(None) def set_parent(self, parent, index=None): if parent is not self.parent: if self.parent: self.parent._remove(self) self.parent = parent if parent: parent._add(self, index) def all_parents(self): widget = self parents = [] while widget.parent: parents.append(widget.parent) widget = widget.parent return parents def _add(self, widget, index=None): if index is not None: self.subwidgets.insert(index, widget) else: self.subwidgets.append(widget) if hasattr(widget, "idleevent"): #print "Adding idle handler for ", widget self.root.add_idle_handler(widget) def _remove(self, widget): if hasattr(widget, "idleevent"): #print "Removing idle handler for ", widget self.root.remove_idle_handler(widget) self.subwidgets.remove(widget) if self.focus_switch is widget: self.focus_switch = None def draw_all(self, surface): if self.visible: surf_rect = surface.get_rect() bg_image = self.bg_image if bg_image: assert isinstance(bg_image, Surface) if self.scale_bg: bg_width, bg_height = bg_image.get_size() width, height = self.size if width > bg_width or height > bg_height: hscale = width / bg_width vscale = height / bg_height bg_image = rotozoom(bg_image, 0.0, max(hscale, vscale)) r = bg_image.get_rect() r.center = surf_rect.center surface.blit(bg_image, r) else: bg = self.bg_color if bg: surface.fill(bg) self.draw(surface) bw = self.border_width if bw: if self.has_focus() and hasattr(self, "highlight_color"): bc = self.highlight_color else: bc = self.border_color or self.fg_color frame_rect(surface, bc, surf_rect, bw) for widget in self.subwidgets: sub_rect = widget.rect if debug_rect: print "Widget: Drawing subwidget %s of %s with rect %s" % ( widget, self, sub_rect) sub_rect = surf_rect.clip(sub_rect) if sub_rect.width > 0 and sub_rect.height > 0: try: sub = surface.subsurface(sub_rect) except ValueError as e: if str(e) == "subsurface rectangle outside surface area": self.diagnose_subsurface_problem(surface, widget) else: raise else: widget.draw_all(sub) self.draw_over(surface) def diagnose_subsurface_problem(self, surface, widget): mess = "Widget %s %s outside parent surface %s %s" % ( widget, widget.rect, self, surface.get_rect()) sys.stderr.write("%s\n" % mess) surface.fill((255, 0, 0), widget.rect) def draw(self, surface): pass def draw_over(self, surface): pass def find_widget(self, pos): for widget in self.subwidgets[::-1]: if widget.visible: r = widget.rect if r.collidepoint(pos): return widget.find_widget(subtract(pos, r.topleft)) return self def handle_mouse(self, name, event): self.augment_mouse_event(event) self.call_handler(name, event) self.setup_cursor(event) def mouse_down(self, event): self.call_parent_handler("mouse_down", event) def mouse_up(self, event): self.call_parent_handler("mouse_up", event) def augment_mouse_event(self, event): event.dict['local'] = self.global_to_local(event.pos) def setup_cursor(self, event): global current_cursor cursor = self.get_cursor(event) or arrow_cursor if cursor is not current_cursor: set_cursor(*cursor) current_cursor = cursor def dispatch_key(self, name, event): if self.visible: if event.type == KEYDOWN: menubar = self._menubar if menubar and menubar.handle_command_key(event): return widget = self.focus_switch if widget: widget.dispatch_key(name, event) else: self.call_handler(name, event) else: self.call_parent_handler(name, event) def get_focus(self): widget = self while 1: focus = widget.focus_switch if not focus: break widget = focus return widget def notify_attention_loss(self): widget = self while 1: if widget.is_modal: break parent = widget.parent if not parent: break focus = parent.focus_switch if focus and focus is not widget: self.root.notMove = False focus.dispatch_attention_loss() widget = parent def dispatch_attention_loss(self): widget = self if hasattr(self, "_highlighted"): self._highlighted = False while widget: widget.attention_lost() widget = widget.focus_switch def attention_lost(self): pass def handle_command(self, name, *args): method = getattr(self, name, None) if method: return method(*args) else: parent = self.next_handler() if parent: return parent.handle_command(name, *args) def next_handler(self): if not self.is_modal: return self.parent def call_handler(self, name, *args): method = getattr(self, name, None) if method: return method(*args) else: return 'pass' def call_parent_handler(self, name, *args): parent = self.next_handler() if parent: parent.call_handler(name, *args) def global_to_local(self, p): return subtract(p, self.local_to_global_offset()) def local_to_global(self, p): return add(p, self.local_to_global_offset()) def local_to_global_offset(self): d = self.topleft parent = self.parent if parent: d = add(d, parent.local_to_global_offset()) return d def key_down(self, event): k = event.key #print "Widget.key_down:", k ### if k == K_RETURN or k == K_KP_ENTER: if self.enter_response is not None: self.dismiss(self.enter_response) return elif k == K_ESCAPE: self.root.fix_sticky_ctrl() if self.cancel_response is not None: self.dismiss(self.cancel_response) return elif k == K_TAB: self.tab_to_next() return self.call_parent_handler('key_down', event) def key_up(self, event): self.call_parent_handler('key_up', event) def is_inside(self, container): widget = self while widget: if widget is container: return True widget = widget.parent return False @property def is_hover(self): return self.root.hover_widget is self def present(self, centered=True): #print "Widget: presenting with rect", self.rect if self.root is None: self.root = self.get_root() if "ControlPanel" not in str(self): self.root.notMove = True if centered: self.center = self.root.center self.root.add(self) try: self.root.run_modal(self) self.dispatch_attention_loss() finally: self.root.remove(self) #print "Widget.present: returning", self.modal_result if "ControlPanel" not in str(self): self.root.notMove = False return self.modal_result def dismiss(self, value=True): self.root.notMove = False self.modal_result = value def get_root(self): return root_widget def get_top_widget(self): top = self while top.parent and not top.is_modal: top = top.parent return top def focus(self): parent = self.next_handler() if parent: parent.focus_on(self) if hasattr(self, "_highlighted"): self._highlighted = True def focus_on(self, subwidget): old_focus = self.focus_switch if old_focus is not subwidget: if old_focus: old_focus.dispatch_attention_loss() self.focus_switch = subwidget self.focus() def has_focus(self): return self.is_modal or (self.parent and self.parent.focused_on(self)) def focused_on(self, widget): return self.focus_switch is widget and self.has_focus() def focus_chain(self): result = [] widget = self while widget: result.append(widget) widget = widget.focus_switch return result def shrink_wrap(self): contents = self.subwidgets if contents: rects = [widget.rect for widget in contents] #rmax = Rect.unionall(rects) # broken in PyGame 1.7.1 rmax = rects.pop() for r in rects: rmax = rmax.union(r) self._rect.size = add(rmax.topleft, rmax.bottomright) #-# Translation live update preparation self.shrink_wrapped = True #-# def invalidate(self): if self.root: self.root.bonus_draw_time = False @staticmethod def get_cursor(event): return arrow_cursor def predict(self, kwds, name): try: return kwds[name] except KeyError: return theme.root.get(self.__class__, name) def predict_attr(self, kwds, name): try: return kwds[name] except KeyError: return getattr(self, name) def init_attr(self, kwds, name): try: return kwds.pop(name) except KeyError: return getattr(self, name) def predict_font(self, kwds, name='font'): return kwds.get(name) or theme.root.get_font(self.__class__, name) def get_margin_rect(self): r = Rect((0, 0), self.size) d = -2 * self.margin r.inflate_ip(d, d) return r def set_size_for_text(self, width, nlines=1): if width is not None: font = self.font d = 2 * self.margin if isinstance(width, basestring): width, height = font.size(width) width += d + 2 else: height = font.size("X")[1] self.size = (width, height * nlines + d) def tab_to_first(self): chain = self.get_tab_order() if chain: chain[0].focus() def _is_next_in_tab(self, top, delta=1): """Helper function to find if the current widget is ne 'next' on when 'tabbing'. :param top: Widget: The 'top' widget to find 'self' in tab order. :param delta: int: The index modifier. Shall be 1 or -1. Defaults to 1. Returns a tuple: (<'self' index in 'top.get_tab_order()' result>, <'top.subwidgets>) If 'self' is not found, the first tuple element is 0, and the second one a tuple of widgets. If self is found, the first elemnt is the index it was found, the second one one a tuple of widgets.""" idx = 0 chain = top.get_tab_order() if self in chain: idx = chain.index(self) + delta return idx, chain def tab_to_next(self): """Give focus to the next focusable widget.""" top = self.get_top_widget() # If SHIFT key is hold down, set the index modifier to -1 to iterate to the previuos widget # instead of the next one. delta = 1 if self.root.get_modifiers()["shift"]: delta = -1 idx, subwidgets = self._is_next_in_tab(top, delta) chain = top.get_tab_order() + subwidgets target = chain[idx % len(chain)] while not target.focusable: _, subwidgets = target._is_next_in_tab(target, delta) chain = chain + subwidgets idx = chain.index(target) + delta target = chain[idx % len(chain)] self.get_focus().dispatch_attention_loss() target.focus() def get_tab_order(self): result = [] self.collect_tab_order(result) return result def collect_tab_order(self, result): if self.visible: if self.tab_stop: result.append(self) for child in self.subwidgets: child.collect_tab_order(result) # def tab_to_first(self, start = None): # if debug_tab: # print "Enter Widget.tab_to_first:", self ### # print "...start =", start ### # if not self.visible: # if debug_tab: print "...invisible" ### # self.tab_to_next_in_parent(start) # elif self.tab_stop: # if debug_tab: print "...stopping here" ### # self.focus() # else: # if debug_tab: print "...tabbing to next" ### # self.tab_to_next(start or self) # if debug_tab: print "Exit Widget.tab_to_first:", self ### # # def tab_to_next(self, start = None): # if debug_tab: # print "Enter Widget.tab_to_next:", self ### # print "...start =", start ### # sub = self.subwidgets # if sub: # if debug_tab: print "...tabbing to first subwidget" ### # sub[0].tab_to_first(start or self) # else: # if debug_tab: print "...tabbing to next in parent" ### # self.tab_to_next_in_parent(start) # if debug_tab: print "Exit Widget.tab_to_next:", self ### # # def tab_to_next_in_parent(self, start): # if debug_tab: # print "Enter Widget.tab_to_next_in_parent:", self ### # print "...start =", start ### # parent = self.parent # if parent and not self.is_modal: # if debug_tab: print "...telling parent to tab to next" ### # parent.tab_to_next_after(self, start) # else: # if self is not start: # if debug_tab: print "...wrapping back to first" ### # self.tab_to_first(start) # if debug_tab: print "Exit Widget.tab_to_next_in_parent:", self ### # # def tab_to_next_after(self, last, start): # if debug_tab: # print "Enter Widget.tab_to_next_after:", self, last ### # print "...start =", start ### # sub = self.subwidgets # i = sub.index(last) + 1 # if debug_tab: print "...next index =", i, "of", len(sub) ### # if i < len(sub): # if debug_tab: print "...tabbing there" ### # sub[i].tab_to_first(start) # else: # if debug_tab: print "...tabbing to next in parent" ### # self.tab_to_next_in_parent(start) # if debug_tab: print "Exit Widget.tab_to_next_after:", self, last ### def inherited(self, attribute): value = getattr(self, attribute) if value is not None: return value else: parent = self.next_handler() if parent: return parent.inherited(attribute) def __contains__(self, event): r = Rect(self._rect) r.left = 0 r.top = 0 p = self.global_to_local(event.pos) return r.collidepoint(p) def get_mouse(self): return self.root.get_mouse_for(self) def get_menu_bar(self): return self._menubar def set_menu_bar(self, menubar): if menubar is not self._menubar: if self._menubar: self.remove(self._menubar) self._menubar = menubar if menubar: if menubar.width == 0: menubar.width = self.width menubar.anchor = 'lr' self.add(menubar) def get_is_gl_container(self): return self._is_gl_container def set_is_gl_container(self, x): self._is_gl_container = x def gl_draw_all(self, root, offset): if not self.visible: return #from OpenGL import GL, GLU rect = self.rect.move(offset) if self.is_gl_container: self.gl_draw_self(root, offset) suboffset = rect.topleft for subwidget in self.subwidgets: subwidget.gl_draw_all(root, suboffset) else: try: surface = Surface(self.size, SRCALPHA) except: #size error? return self.draw_all(surface) data = image.tostring(surface, 'RGBA', 1) w, h = root.size GL.glViewport(0, 0, w, h) GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GLU.gluOrtho2D(0, w, 0, h) GL.glMatrixMode(GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glRasterPos2i(max(rect.left, 0), max(h - rect.bottom, 0)) GL.glPushAttrib(GL.GL_COLOR_BUFFER_BIT) GL.glEnable(GL.GL_BLEND) GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA) GL.glDrawPixels(self.width, self.height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, fromstring(data, dtype='uint8')) GL.glPopAttrib() GL.glFlush() def gl_draw_self(self, root, offset): pass
28,228
32.969916
162
py
MCEdit-Unified
MCEdit-Unified-master/albow/screen.py
# # Albow - Screen # from widget import Widget #------------------------------------------------------------------------------ class Screen(Widget): def __init__(self, shell, **kwds): Widget.__init__(self, shell.rect, **kwds) self.shell = shell self.center = shell.center def begin_frame(self): pass def enter_screen(self): pass def leave_screen(self): pass
429
16.916667
79
py
MCEdit-Unified
MCEdit-Unified-master/albow/__init__.py
"""ALBOW - A Little Bit of Widgetry for PyGame by Gregory Ewing [email protected] """ update_translation = False # Register unparented widgets in this to track them. unparented = {} from version import version from albow.controls import Label, Button, Image, AttrRef, ItemRef, \ RadioButton, ValueDisplay, SmallLabel, SmallValueDisplay, CheckBox, ValueButton, ButtonBase from albow.layout import Row, Column, Grid, Frame from albow.fields import TextField, FloatField, IntField, TimeField, TextFieldWrapped, Field from albow.shell import Shell from albow.screen import Screen from albow.text_screen import TextScreen from albow.resource import get_font, get_image from albow.grid_view import GridView from albow.palette_view import PaletteView from albow.image_array import get_image_array from albow.dialogs import alert, ask, input_text, input_text_buttons from albow.file_dialogs import \ request_old_filename, request_new_filename, look_for_file_or_directory from albow.tab_panel import TabPanel from albow.table_view import TableView, TableColumn from albow.widget import Widget from albow.menu import Menu # -# Remove the folowing line when file_opener.py is moved from albow.file_opener import FileOpener from albow.tree import Tree from scrollpanel import ScrollPanel from extended_widgets import ChoiceButton, HotkeyColumn, MenuButton, CheckBoxLabel, FloatInputRow, IntInputRow, showProgress, TextInputRow
1,438
37.891892
138
py
MCEdit-Unified
MCEdit-Unified-master/albow/table_view.py
# # Albow - Table View # #-# Modified by D.C.-G. for translation purpose from pygame import Rect from layout import Column from palette_view import PaletteView from utils import blit_in_rect from translate import _ class TableView(Column): columns = [] header_font = None header_fg_color = None header_bg_color = None header_spacing = 5 column_margin = 2 def __init__(self, nrows=15, height=None, header_height=None, row_height=None, scrolling=True, **kwds): columns = self.predict_attr(kwds, 'columns') if row_height is None: font = self.predict_font(kwds) row_height = font.get_linesize() if header_height is None: self.header_height = header_height = row_height row_width = 0 if columns: for column in columns: row_width += column.width row_width += 2 * self.column_margin * len(columns) contents = [] header = None if header_height: header = TableHeaderView(row_width, header_height) contents.append(header) row_size = (row_width, row_height) if not nrows and height: nrows = height // row_height self.rows = rows = TableRowView(row_size, nrows or 10, scrolling=scrolling) contents.append(rows) s = self.header_spacing Column.__init__(self, contents, align='l', spacing=s, **kwds) if header: header.font = self.header_font or self.font header.fg_color = self.header_fg_color or self.fg_color header.bg_color = self.header_bg_color or self.bg_color rows.font = self.font rows.fg_color = self.fg_color rows.bg_color = self.bg_color rows.sel_color = self.sel_color def column_info(self, row_data): columns = self.columns m = self.column_margin d = 2 * m x = 0 for i, column in enumerate(columns): width = column.width if row_data: data = row_data[i] else: data = None yield i, x + m, width - d, column, data x += width def draw_header_cell(self, surf, i, cell_rect, column): self.draw_text_cell(surf, i, column.title, cell_rect, column.alignment, self.font) def draw_table_cell(self, surf, i, data, cell_rect, column): text = column.format(data) self.draw_text_cell(surf, i, text, cell_rect, column.alignment, self.font) def draw_text_cell(self, surf, i, data, cell_rect, align, font): buf = font.render(unicode(data), True, self.fg_color) blit_in_rect(surf, buf, cell_rect, align) @staticmethod def row_is_selected(n): return False def click_row(self, n, e): pass @staticmethod def click_column_header(col): print "click_column_header: ", col def click_header(self, n, e): x, y = self.global_to_local(e.pos) width = 0 for col in self.columns: width += col.width if x < width: return self.click_column_header(col) class TableColumn(object): # title string # width int # alignment 'l' or 'c' or 'r' # formatter func(data) -> string # format_string string Used by default formatter format_string = "%s" def __init__(self, title, width, align='l', fmt=None): self.title = _(title) self.width = width self.alignment = align if fmt: if isinstance(fmt, (str, unicode)): self.format_string = fmt else: self.formatter = fmt def format(self, data): if data is not None: return self.formatter(_(data)) else: return "" def formatter(self, data): return self.format_string % _(data) class TableRowBase(PaletteView): def __init__(self, cell_size, nrows, scrolling): PaletteView.__init__(self, cell_size, nrows, 1, scrolling=scrolling) def num_items(self): return self.parent.num_rows() def draw_item(self, surf, row, row_rect): table = self.parent height = row_rect.height row_data = self.row_data(row) for i, x, width, column, cell_data in table.column_info(row_data): cell_rect = Rect(x + self.margin, row_rect.top, width, height) self.draw_table_cell(surf, row, cell_data, cell_rect, column) def row_data(self, row): return self.parent.row_data(row) def draw_table_cell(self, surf, i, data, cell_rect, column): self.parent.draw_table_cell(surf, i, data, cell_rect, column) class TableRowView(TableRowBase): highlight_style = 'fill' vstretch = True def item_is_selected(self, n): return self.parent.row_is_selected(n) def click_item(self, n, e): self.parent.click_row(n, e) class TableHeaderView(TableRowBase): def __init__(self, width, height): TableRowBase.__init__(self, (width, height), 1, False) # def row_data(self, row): # return [c.title for c in self.parent.columns] # def draw_table_cell(self, surf, i, text, cell_rect, column): # self.parent.draw_header_cell(surf, i, text, cell_rect, column) def row_data(self, row): pass def draw_table_cell(self, surf, i, data, cell_rect, column): self.parent.draw_header_cell(surf, i, cell_rect, column) def click_item(self, n, e): self.parent.click_header(n, e)
5,676
30.192308
83
py
MCEdit-Unified
MCEdit-Unified-master/albow/fields.py
# # Albow - Fields # # - # Modified by D.C.-G. for translation purpose from pygame import draw import traceback import pygame from pygame import key # noinspection PyUnresolvedReferences from pygame.locals import K_LEFT, K_RIGHT, K_TAB, K_c, K_v, K_x, SCRAP_TEXT, K_UP, K_DOWN, K_RALT, K_LALT, \ K_BACKSPACE, K_DELETE, KMOD_SHIFT, KMOD_CTRL, KMOD_ALT, KMOD_META, K_HOME, K_END, K_z, K_y, K_KP2, K_KP1 from widget import Widget, overridable_property from controls import Control # This need to be changed. We need albow.translate in the config module. # he solution can be a set of functions wich let us define the needed MCEdit 'config' data # without importing it. # It can be a 'config' module built only for albow. from config import config from translate import _ import pyperclip class TextEditor(Widget): upper = False tab_stop = True _text = u"" def __init__(self, width, upper=None, **kwds): kwds['doNotTranslate'] = kwds.get('doNotTranslate', True) Widget.__init__(self, **kwds) self.set_size_for_text(width) if upper is not None: self.upper = upper self.insertion_point = None self.selection_end = None self.selection_start = None self.undoList = [] self.undoNum = 0 self.redoList = [] self.root = self.get_root() def get_text(self): return self._text def set_text(self, text): if isinstance(text, str): try: text = unicode(text, 'utf-8') except (UnicodeEncodeError, UnicodeDecodeError): print "Failed to convert text to unicode, skipping set text" traceback.print_exc() self._text = _(text, doNotTranslate=self.doNotTranslate) text = overridable_property('text') def draw(self, surface): frame = self.get_margin_rect() fg = self.fg_color font = self.font focused = self.has_focus() text, i = self.get_text_and_insertion_point() if focused and i is None: if self.selection_start is None or self.selection_end is None: surface.fill(self.sel_color, frame) else: startStep = self.selection_start endStep = self.selection_end if startStep > endStep: x1, h = font.size(text[0:endStep])[0], font.get_linesize() x2, h = font.size(text[0:startStep])[0], font.get_linesize() x1 += frame.left x2 += frame.left y = frame.top selRect = pygame.Rect(x1, y, (x2 - x1), h) else: x1, h = font.size(text[0:startStep])[0], font.get_linesize() x2, h = font.size(text[0:endStep])[0], font.get_linesize() x1 += frame.left x2 += frame.left y = frame.top selRect = pygame.Rect(x1, y, (x2 - x1), h) draw.rect(surface, self.sel_color, selRect) image = font.render(text, True, fg) surface.blit(image, frame) if focused and i is not None: x, h = font.size(text[:i]) #[0], font.get_linesize() x += frame.left y = frame.top draw.line(surface, fg, (x, y), (x, y + h - 1)) def key_down(self, event): self.root.notMove = True if not event.cmd or (event.alt and event.unicode): k = event.key if k == K_LEFT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(-1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_end is None and self.insertion_point != 0: self.selection_start = self.insertion_point self.selection_end = self.insertion_point - 1 self.insertion_point = None elif self.selection_end is not None and self.selection_end != 0: self.selection_end -= 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_RIGHT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_start is None and self.insertion_point < len(self.text): self.selection_start = self.insertion_point self.selection_end = self.insertion_point + 1 self.insertion_point = None elif self.selection_start is not None and self.selection_end < len(self.text): self.selection_end += 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_TAB: self.attention_lost() self.tab_to_next() return if k == K_HOME: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = 0 elif self.insertion_point != 0: if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = 0 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_END: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = len(self.text) elif self.insertion_point != len(self.text): if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = len(self.text) if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return try: c = event.unicode except ValueError: print 'value error' c = "" if self.insert_char(c, k) != 'pass': return if event.cmd and event.unicode: if event.key == K_c or event.key == K_x: try: # pygame.scrap.put(SCRAP_TEXT, self.text) text, i = self.get_text_and_insertion_point() if i is None and (self.selection_start is None or self.selection_end is None): text = self.text elif i is None and self.selection_start is not None and self.selection_end is not None: text = text[(min(self.selection_start, self.selection_end)):max(self.selection_start, self.selection_end)] else: return pyperclip.copy(text) except: print "scrap not available" finally: if event.key == K_x and i is None: self.insert_char(event.unicode, K_BACKSPACE) elif event.key == K_v: try: self.addUndo() # t = pygame.scrap.get(SCRAP_TEXT).replace('\0', '') t = pyperclip.paste().replace("\n", " ") if t is not None: allow = True for char in t: if not self.allow_char(char): allow = False if not allow: return if self.insertion_point is not None: self.text = self.text[:self.insertion_point] + t + self.text[self.insertion_point:] self.insertion_point += len(t) elif self.insertion_point is None and ( self.selection_start is None or self.selection_end is None): self.text = t self.insertion_point = len(t) elif self.insertion_point is None and self.selection_start is not None and self.selection_end is not None: self.text = self.text[:(min(self.selection_start, self.selection_end))] + t + self.text[( max(self.selection_start, self.selection_end)):] self.selection_start = None self.selection_end = None else: return self.change_text(self.text) except: print "scrap not available" # print repr(t) elif event.key == K_z and self.undoNum > 0: self.redoList.append(self.text) self.undoNum -= 1 self.change_text(self.undoList[self.undoNum]) self.insertion_point = len(self.text) self.selection_start = None self.selection_end = None elif event.key == K_y and len(self.undoList) > self.undoNum: self.undoNum += 1 self.change_text(self.redoList[-1]) self.redoList = self.redoList[:-1] self.insertion_point = len(self.text) self.selection_start = None self.selection_end = None else: self.attention_lost() self.parent.dispatch_key(self.root.getKey(event), event) def key_up(self, event): pass def get_text_and_insertion_point(self): text = self.get_text() i = self.insertion_point if i is not None: i = max(0, min(i, len(text))) return text, i def move_insertion_point(self, d): self.selection_start = None self.selection_end = None text, i = self.get_text_and_insertion_point() if i is None: if d > 0: i = len(text) else: i = 0 else: i = max(0, min(i + d, len(text))) self.insertion_point = i def insert_char(self, c, k=None): self.addUndo() if self.upper: c = c.upper() if (k == K_BACKSPACE or k == K_DELETE) and self.enabled: text, i = self.get_text_and_insertion_point() if i is None: text = u"" i = 0 else: if k == K_BACKSPACE: text = text[:i - 1] + text[i:] i -= 1 else: text = text[:i] + text[i + 1:] self.change_text(text) self.insertion_point = i return elif c == "\r" or c == "\x03": return self.call_handler('enter_action') elif c == "\x1b": return self.call_handler('escape_action') elif c >= "\x20" and self.enabled: if self.allow_char(c): text, i = self.get_text_and_insertion_point() if i is None: text = c i = 1 else: text = text[:i] + c + text[i:] i += 1 self.change_text(text) self.insertion_point = i return return 'pass' def escape_action(self, *args): self.call_parent_handler('escape_action', *args) def addUndo(self): if len(self.undoList) > self.undoNum: self.undoList = self.undoList[:self.undoNum] self.undoList.append(self.text) self.undoNum += 1 self.redoList = [] def allow_char(self, c): return True def mouse_down(self, e): self.root.notMove = True self.focus() self.selection_start = None self.selection_end = None if e.num_clicks == 2: self.insertion_point = None return x, y = e.local i = self.pos_to_index(x) self.insertion_point = i def pos_to_index(self, x): text = self.get_text() font = self.font def width(i): return font.size(text[:i])[0] i1 = 0 i2 = len(text) x1 = 0 x2 = width(i2) while i2 - i1 > 1: i3 = (i1 + i2) // 2 x3 = width(i3) if x > x3: i1, x1 = i3, x3 else: i2, x2 = i3, x3 if x - x1 > (x2 - x1) // 2: i = i2 else: i = i1 return i def change_text(self, text): self.set_text(text) self.call_handler('change_action') # -------------------------------------------------------------------------- class Field(TextEditor, Control): # type func(string) -> value # editing boolean empty = NotImplemented format = u"%s" min = None max = None enter_passes = False def __init__(self, width=None, **kwds): mi = self.predict_attr(kwds, 'min') ma = self.predict_attr(kwds, 'max') if 'format' in kwds: self.format = kwds.pop('format') if 'empty' in kwds: self.empty = kwds.pop('empty') self.editing = False if width is None: w1 = w2 = "" if mi is not None: w1 = self.format_value(mi) if ma is not None: w2 = self.format_value(ma) if w2: if len(w1) > len(w2): width = w1 else: width = w2 if width is None: width = 100 TextEditor.__init__(self, width, **kwds) def format_value(self, x): if x == self.empty: return "" else: return self.format % x def get_text(self): if self.editing: return self._text else: return self.format_value(self.value) def set_text(self, text): if isinstance(text, str): try: text = unicode(text, 'utf-8') except (UnicodeEncodeError, UnicodeDecodeError): print "Failed to convert text to unicode, skipping set text" traceback.print_exc() self.editing = True self._text = _(text, doNotTranslate=self.doNotTranslate) if self.should_commit_immediately(text): self.commit() def should_commit_immediately(self, text): return False def enter_action(self): if self.editing: self.commit() elif self.enter_passes: return 'pass' def escape_action(self): if self.editing: self.editing = False self.insertion_point = None else: return TextEditor.escape_action(self) def attention_lost(self): self.commit(notify=True) def clamp_value(self, value): if self.max: value = min(value, self.max) if self.min: value = max(value, self.min) return value def commit(self, notify=False): if self.editing: text = self._text if text: try: value = self.type(text) except ValueError: return value = self.clamp_value(value) else: value = self.empty if value is NotImplemented: return self.value = value self.insertion_point = None if notify: self.change_text(unicode(value)) else: self._text = unicode(value) self.editing = False else: self.insertion_point = None # def get_value(self): # self.commit() # return Control.get_value(self) # # def set_value(self, x): # Control.set_value(self, x) # self.editing = False #--------------------------------------------------------------------------- class TextField(Field): type = unicode _value = u"" def should_commit_immediately(self, text): return True class IntField(Field): tooltipText = _("Point here and use mousewheel to adjust") @staticmethod def type(i): try: return eval(i) except: try: return int(i) except: return 0 _shift_increment = 16 _increment = 1 @property def increment(self): fastIncrementModifier = config.keys.fastIncrementModifierHold.get() if (fastIncrementModifier == "Shift" and key.get_mods() & KMOD_SHIFT) or (fastIncrementModifier == "Ctrl" and (key.get_mods() & KMOD_CTRL) or (key.get_mods() & KMOD_META)) or (fastIncrementModifier == "Alt" and key.get_mods() & KMOD_ALT): return self._shift_increment return self._increment @increment.setter def increment(self, val): self._increment = val def decrease_value(self): self.value = self.clamp_value(self.value - self.increment) def increase_value(self): self.value = self.clamp_value(self.value + self.increment) def mouse_down(self, evt): if evt.button == 5: self.decrease_value() self.change_text(str(self.value)) elif evt.button == 4: self.increase_value() self.change_text(str(self.value)) else: Field.mouse_down(self, evt) allowed_chars = '-+*/<>()0123456789' def allow_char(self, c): return c in self.allowed_chars def should_commit_immediately(self, text): while len(text) > 1 and text[0] == '0': text = text[1:] self._text = text try: return str(eval(text)) == text except: return False class TimeField(Field): allowed_chars = ':0123456789 APMapm' def format_value(self, hm): format = "%02d:%02d" h, m = hm if h >= 12: h -= 12 return format % (h or 12, m) + " PM" else: return format % (h or 12, m) + " AM" def allow_char(self, c): return c in self.allowed_chars @staticmethod def type(i): h, m = 0, 0 i = i.upper() pm = "PM" in i for a in "APM": i = i.replace(a, "") parts = i.split(":") if len(parts): h = int(parts[0]) if len(parts) > 1: m = int(parts[1]) if pm and h < 12: h += 12 h %= 24 m %= 60 return h, m def mouse_down(self, evt): if evt.button == 5: delta = -1 elif evt.button == 4: delta = 1 else: return Field.mouse_down(self, evt) (h, m) = self.value pos = self.pos_to_index(evt.local[0]) if pos < 3: h += delta elif pos < 6: m += delta else: h = (h + 12) % 24 self.value = (h, m) def set_value(self, v): h, m = v super(TimeField, self).set_value((h % 24, m % 60)) class FloatField(Field): type = float _increment = 0.1 zero = 0.000000000001 _shift_increment = 16.0 tooltipText = _("Point here and use mousewheel to adjust") allowed_chars = '-+.0123456789' def allow_char(self, c): return c in self.allowed_chars @property def increment(self): fastIncrementModifier = config.keys.fastIncrementModifierHold.get() if (fastIncrementModifier == "Shift" and key.get_mods() & KMOD_SHIFT) or (fastIncrementModifier == "Ctrl" and (key.get_mods() & KMOD_CTRL) or (key.get_mods() & KMOD_META)) or (fastIncrementModifier == "Alt" and key.get_mods() & KMOD_ALT): return self._shift_increment return self._increment @increment.setter def increment(self, val): self._increment = self.clamp_value(val) def decrease_value(self): if abs(self.value - self.increment) < self.zero: self.value = self.clamp_value(0.0) else: self.value = self.clamp_value(self.value - self.increment) def increase_value(self): if abs(self.value + self.increment) < self.zero: self.value = self.clamp_value(0.0) else: self.value = self.clamp_value(self.value + self.increment) def mouse_down(self, evt): if evt.button == 5: self.decrease_value() self.change_text(str(self.value)) elif evt.button == 4: self.increase_value() self.change_text(str(self.value)) else: Field.mouse_down(self, evt) #--------------------------------------------------------------------------- class TextEditorWrapped(Widget): upper = False tab_stop = True _text = u"" def __init__(self, width, lines, upper=None, allowed_chars=None, **kwds): kwds['doNotTranslate'] = kwds.get('doNotTranslate', True) Widget.__init__(self, **kwds) self.set_size_for_text(width, lines) if upper: self.upper = upper self.insertion_point = None self.insertion_step = None self.insertion_line = None self.selection_start = None self.selection_end = None self.topLine = 0 self.dispLines = lines self.textChanged = True self.allowed_chars = allowed_chars self.undoList = [] self.undoNum = 0 self.redoList = [] self.root = self.get_root() self.alt21 = False def get_text(self): return self._text def set_text(self, text): if isinstance(text, str): try: text = unicode(text, 'utf-8') except (UnicodeEncodeError, UnicodeDecodeError): print "Failed to convert text to unicode, skipping set text" traceback.print_exc() self._text = _(text, doNotTranslate=self.doNotTranslate) self.textChanged = True text = overridable_property('text') #Text line list and text line EoL index reference textL = [] textRefList = [] def draw(self, surface): frame = self.get_margin_rect() fg = self.fg_color font = self.font linesize = font.get_linesize() focused = self.has_focus() text, i, il = self.get_text_and_insertion_data() ip = self.insertion_point self.doFix = True self.updateTextWrap() #Scroll the text up or down if necessary if self.insertion_line > self.topLine + self.dispLines - 1: if ip == len(text): self.scroll_down_all() else: self.scroll_down() elif self.insertion_line < self.topLine: if ip == 0: self.scroll_up_all() else: self.scroll_up() #Draw Border draw.rect(surface, self.sel_color, pygame.Rect(frame.left, frame.top, frame.size[0], frame.size[1]), 1) #Draw Selection Highlighting if Applicable if focused and ip is None: if self.selection_start is None or self.selection_end is None: surface.fill(self.sel_color, frame) else: startLine, startStep = self.get_char_position(self.selection_start) endLine, endStep = self.get_char_position(self.selection_end) rects = [] if startLine == endLine: if startStep > endStep: x1, h = font.size(self.textL[startLine][0:endStep])[0], font.get_linesize() x2, h = font.size(self.textL[startLine][0:startStep])[0], font.get_linesize() x1 += frame.left x2 += frame.left lineOffset = startLine - self.topLine y = frame.top + lineOffset * h if lineOffset >= 0: selRect = pygame.Rect(x1, y, (x2 - x1), h) else: x1, h = font.size(self.textL[startLine][0:startStep])[0], font.get_linesize() x2, h = font.size(self.textL[startLine][0:endStep])[0], font.get_linesize() x1 += frame.left x2 += frame.left lineOffset = startLine - self.topLine y = frame.top + lineOffset * h if lineOffset >= 0: selRect = pygame.Rect(x1, y, (x2 - x1), h) draw.rect(surface, self.sel_color, selRect) elif startLine < endLine: x1, h = font.size(self.textL[startLine][0:startStep])[0], font.get_linesize() x2, h = font.size(self.textL[endLine][0:endStep])[0], font.get_linesize() x1 += frame.left x2 += frame.left lineOffsetS = startLine - self.topLine lineOffsetE = endLine - self.topLine lDiff = lineOffsetE - lineOffsetS while lDiff > 1 and 0 <= lDiff + lineOffsetS + lDiff < self.dispLines: y = frame.top + lineOffsetS * h + (lDiff - 1) * h rects.append(pygame.Rect(frame.left, y, frame.right - frame.left, h)) lDiff += -1 y = frame.top + lineOffsetS * h if lineOffsetS >= 0: rects.append(pygame.Rect(x1, y, frame.right - x1, h)) y = frame.top + lineOffsetE * h if lineOffsetE < self.dispLines: rects.append(pygame.Rect(frame.left, y, x2 - frame.left, h)) for selRect in rects: draw.rect(surface, self.sel_color, selRect) elif startLine > endLine: x2, h = font.size(self.textL[startLine][0:startStep])[0], font.get_linesize() x1, h = font.size(self.textL[endLine][0:endStep])[0], font.get_linesize() x1 += frame.left x2 += frame.left lineOffsetE = startLine - self.topLine lineOffsetS = endLine - self.topLine lDiff = lineOffsetE - lineOffsetS while lDiff > 1 and 0 <= lDiff + lineOffsetS + lDiff < self.dispLines: y = frame.top + lineOffsetS * h + (lDiff - 1) * h rects.append(pygame.Rect(frame.left, y, frame.right - frame.left, h)) lDiff += -1 y = frame.top + lineOffsetS * h if lineOffsetS >= 0: rects.append(pygame.Rect(x1, y, frame.right - x1, h)) y = frame.top + lineOffsetE * h if lineOffsetE < self.dispLines: rects.append(pygame.Rect(frame.left, y, x2 - frame.left, h)) for selRect in rects: draw.rect(surface, self.sel_color, selRect) # Draw Lines of Text h = 0 for textLine in self.textL[self.topLine:self.topLine + self.dispLines]: image = font.render(textLine, True, fg) surface.blit(image, frame.move(0, h)) # h += font.size(textLine)[1] h += linesize # Draw Cursor if Applicable if focused and ip is not None and i is not None and il is not None: if self.textL: # x, h = font.size(self.textL[il][:i]) x, h = font.size(self.textL[il][:i])[0], linesize else: # x, h = (0, font.size("X")[1]) x, h = (0, linesize) if self.textRefList and ip == self.textRefList[il]: if self.doFix: self.move_insertion_point(-1) self.doFix = False x += font.size(self.textL[il][i])[0] if not self.doFix: self.move_insertion_point(1) x += frame.left y = frame.top + h * (il - self.topLine) draw.line(surface, fg, (x, y), (x, y + h - 1)) def key_down(self, event): # Ugly ALT + 21 hack if self.alt21 and event.key == K_KP1 and event.alt: self.insert_char(u"\xa7") self.alt21 = False return elif self.alt21: self.insert_char(u"2") self.alt21 = False if event.alt and event.key == K_KP2: self.alt21 = True return self.root.notMove = True if not event.cmd or (event.alt and event.unicode): k = event.key if k == K_LEFT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(-1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_end is None and self.insertion_point != 0: self.selection_start = self.insertion_point self.selection_end = self.insertion_point - 1 self.insertion_point = None elif self.selection_end is not None and self.selection_end != 0: self.selection_end -= 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_RIGHT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_start is None and self.insertion_point < len(self.text): self.selection_start = self.insertion_point self.selection_end = self.insertion_point + 1 self.insertion_point = None elif self.selection_start is not None and self.selection_end < len(self.text): self.selection_end += 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_TAB: self.attention_lost() self.tab_to_next() return if k == K_DOWN: self.move_insertion_line(1) return if k == K_UP: self.move_insertion_line(-1) return if k == K_HOME: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = 0 self.sync_line_and_step() elif self.insertion_point != 0: if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = 0 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None self.sync_line_and_step() return if k == K_END: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = len(self.text) self.sync_line_and_step() elif self.insertion_point != len(self.text): if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = len(self.text) if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None self.sync_line_and_step() return try: c = event.unicode except ValueError: print 'value error' c = "" if self.insert_char(c, k) != 'pass': return if event.cmd and event.unicode: if event.key == K_c or event.key == K_x: try: text, i = self.get_text_and_insertion_point() if i is None and (self.selection_start is None or self.selection_end is None): text = self.text elif i is None and self.selection_start is not None and self.selection_end is not None: text = text[(min(self.selection_start, self.selection_end)):max(self.selection_start, self.selection_end)] else: return pyperclip.copy(text) except: print "scrap not available" finally: if event.key == K_x and i is None: self.insert_char(event.unicode, K_BACKSPACE) elif event.key == K_v: try: self.addUndo() # t = pygame.scrap.get(SCRAP_TEXT).replace('\0', '') t = pyperclip.paste().replace("\n", " ") if t is not None: allow = True for char in t: if not self.allow_char(char): allow = False if not allow: return if self.insertion_point is not None: self.text = self.text[:self.insertion_point] + t + self.text[self.insertion_point:] self.insertion_point += len(t) elif self.insertion_point is None and ( self.selection_start is None or self.selection_end is None): self.text = t self.insertion_point = len(t) elif self.insertion_point is None and self.selection_start is not None and self.selection_end is not None: self.text = self.text[:(min(self.selection_start, self.selection_end))] + t + self.text[( max(self.selection_start, self.selection_end)):] self.selection_start = None self.selection_end = None else: return self.change_text(self.text) self.sync_line_and_step() except: print "scrap not available" # print repr(t) elif event.key == K_z and self.undoNum > 0: self.redoList.append(self.text) self.undoNum -= 1 self.change_text(self.undoList[self.undoNum]) self.insertion_point = len(self.text) self.selection_start = None self.selection_end = None elif event.key == K_y and len(self.undoList) > self.undoNum: self.undoNum += 1 self.change_text(self.redoList[-1]) self.redoList = self.redoList[:-1] self.insertion_point = len(self.text) self.selection_start = None self.selection_end = None else: self.attention_lost() # self.parent.dispatch_key(evt) def key_up(self, event): pass def get_text_and_insertion_point(self): text = self.get_text() i = self.insertion_point if i is not None: i = max(0, min(i, len(text))) return text, i def get_text_and_insertion_data(self): text = self.get_text() i = self.insertion_step il = self.insertion_line if il is not None: il = max(0, min(il, (len(self.textL) - 1))) if i is not None and il is not None and len(self.textL) > 0: i = max(0, min(i, len(self.textL[il]) - 1)) return text, i, il def move_insertion_point(self, d): self.selection_end = None self.selection_start = None text, i = self.get_text_and_insertion_point() if i is None: if d > 0: i = len(text) else: i = 0 else: i = max(0, min(i + d, len(text))) self.insertion_point = i self.sync_line_and_step() def sync_line_and_step(self): self.updateTextWrap() self.sync_insertion_line() self.sync_insertion_step() def sync_insertion_line(self): ip = self.insertion_point i = 0 for refVal in self.textRefList: if ip > refVal: i += 1 elif ip <= refVal: break self.insertion_line = i def sync_insertion_step(self): ip = self.insertion_point il = self.insertion_line if ip is None: self.move_insertion_point(0) ip = self.insertion_point if il is None: self.move_insertion_line(0) il = self.insertion_line if il > 0: refPoint = self.textRefList[il - 1] else: refPoint = 0 self.insertion_step = ip - refPoint def get_char_position(self, i): j = 0 for refVal in self.textRefList: if i > refVal: j += 1 elif i <= refVal: break line = j if line > 0: refPoint = self.textRefList[line - 1] else: refPoint = 0 step = i - refPoint return line, step def move_insertion_line(self, d): text, i, il = self.get_text_and_insertion_data() if self.selection_end is not None: endLine, endStep = self.get_char_position(self.selection_end) il = endLine i = endStep self.insertion_step = i self.selection_end = None self.selection_start = None if il is None: if d > 0: if len(self.textL) > 1: self.insertion_line = d else: self.insertion_line = 0 else: self.insertion_line = 0 if i is None: self.insertion_step = 0 elif 0 <= d + il + d < len(self.textL): self.insertion_line = il + d if self.insertion_line > 0: self.insertion_point = self.textRefList[self.insertion_line - 1] + self.insertion_step if self.insertion_point > len(self.text): self.insertion_point = len(self.text) else: if self.insertion_step is not None: self.insertion_point = self.insertion_step else: self.insertion_point = 0 self.insertion_step = 0 def insert_char(self, c, k=None): self.addUndo() if self.upper: c = c.upper() if (k == K_BACKSPACE or k == K_DELETE) and self.enabled: text, i = self.get_text_and_insertion_point() if i is None and (self.selection_start is None or self.selection_end is None): text = "" i = 0 self.insertion_line = i self.insertion_step = i elif i is None and self.selection_start is not None and self.selection_end is not None: i = min(self.selection_start, self.selection_end) text = text[:(min(self.selection_start, self.selection_end))] + text[( max(self.selection_start, self.selection_end)):] self.selection_start = None self.selection_end = None elif i >= 0: if k == K_BACKSPACE and i > 0: text = text[:i - 1] + text[i:] i -= 1 elif k == K_DELETE: text = text[:i] + text[i + 1:] self.change_text(text) self.insertion_point = i self.sync_line_and_step() return elif c == "\r" or c == "\x03": return self.call_handler('enter_action') elif c == "\x1b": return self.call_handler('escape_action') elif c >= "\x20" and self.enabled: if self.allow_char(c): text, i = self.get_text_and_insertion_point() if i is None and (self.selection_start is None or self.selection_end is None): text = c i = 1 elif i is None and self.selection_start is not None and self.selection_end is not None: i = min(self.selection_start, self.selection_end) + 1 text = text[:(min(self.selection_start, self.selection_end))] + c + text[( max(self.selection_start, self.selection_end)):] self.selection_start = None self.selection_end = None else: text = text[:i] + c + text[i:] i += 1 self.change_text(text) self.insertion_point = i self.sync_line_and_step() return return 'pass' def escape_action(self, *args, **kwargs): self.call_parent_handler('escape_action', *args) def addUndo(self): if len(self.undoList) > self.undoNum: self.undoList = self.undoList[:self.undoNum] self.undoList.append(self.text) self.undoNum += 1 self.redoList = [] def allow_char(self, c): if not self.allowed_chars: return True return c in self.allowed_chars def mouse_down(self, e): self.root.notMove = True self.focus() if e.button == 1: if e.num_clicks == 2: self.insertion_point = None self.selection_start = None self.selection_end = None return x, y = e.local i = self.pos_to_index(x, y) self.insertion_point = i self.selection_start = None self.selection_end = None self.sync_line_and_step() if e.button == 5: # self.scroll_down() self.move_insertion_line(1) if e.button == 4: # self.scroll_up() self.move_insertion_line(-1) def mouse_drag(self, e): x, y = e.local i = self.pos_to_index(x, y) if self.insertion_point is not None: if i != self.insertion_point: if self.selection_start is None: self.selection_start = self.insertion_point self.selection_end = i self.insertion_point = None else: if self.selection_start is None: self.selection_start = i else: if self.selection_start == i: self.selection_start = None self.selection_end = None self.insertion_point = i else: self.selection_end = i def pos_to_index(self, x, y): textL = self.textL textRef = self.textRefList topLine = self.topLine dispLines = self.dispLines font = self.font if textL: h = font.get_linesize() line = y // h if line >= dispLines: line = dispLines - 1 line += topLine if line >= len(textL): line = len(textL) - 1 if line < 0: line = 0 def width(i): return font.size(textL[line][:i])[0] i1 = 0 i2 = len(textL[line]) x1 = 0 x2 = width(i2) while i2 - i1 > 1: i3 = (i1 + i2) // 2 x3 = width(i3) if x > x3: i1, x1 = i3, x3 else: i2, x2 = i3, x3 if x - x1 > (x2 - x1) // 2: i = i2 else: i = i1 if line > 0: i = i + textRef[line - 1] else: i = 0 return i def change_text(self, text): self.set_text(_(text, doNotTranslate=self.doNotTranslate)) self.textChanged = True self.updateTextWrap() self.call_handler('change_action') def scroll_up(self): if self.topLine - 1 >= 0: self.topLine -= 1 def scroll_down(self): if self.topLine + 1 < len(self.textL) - self.dispLines + 1: self.topLine += 1 def scroll_up_all(self): if self.topLine - 1 >= 0: self.topLine = 0 def scroll_down_all(self): if self.topLine + 1 < len(self.textL) - self.dispLines + 1: self.topLine = len(self.textL) - self.dispLines def updateTextWrap(self): # Update text wrapping for box font = self.font frame = self.get_margin_rect() frameW, frameH = frame.size if self.textChanged: ix = 0 iz = 0 textLi = 0 text = self.text textL = [] textR = [] while ix < len(text): ix += 1 if ix == '\r' or ix == '\x03' or ix == '\n': print("RETURN FOUND") if len(textL) > textLi: textL[textLi] = text[iz:ix] textR[textLi] = ix else: textL.append(text[iz:ix]) textR.append(ix) iz = ix + 1 textLi += 1 segW = font.size(text[iz:ix])[0] if segW > frameW: if len(textL) > textLi: textL[textLi] = text[iz:ix - 1] textR[textLi] = ix - 1 else: textL.append(text[iz:ix - 1]) textR.append(ix - 1) iz = ix - 1 textLi += 1 if iz < ix: if len(textL) > textLi: textL[textLi] = text[iz:ix] textR[textLi] = ix else: textL.append(text[iz:ix]) textR.append(ix) iz = ix textLi += 1 textL = textL[:textLi] textR = textR[:textLi] self.textL = textL self.textRefList = textR self.textChanged = False i = 0 # --------------------------------------------------------------------------- class FieldWrapped(TextEditorWrapped, Control): # type func(string) -> value # editing boolean empty = "" format = u"%s" min = None max = None enter_passes = False def __init__(self, width=None, lines=1, allowed_chars=None, **kwds): min = self.predict_attr(kwds, 'min') max = self.predict_attr(kwds, 'max') if 'format' in kwds: self.format = kwds.pop('format') if 'empty' in kwds: self.empty = kwds.pop('empty') self.editing = False if width is None: w1 = w2 = "" if min is not None: w1 = self.format_value(min) if max is not None: w2 = self.format_value(max) if w2: if len(w1) > len(w2): width = w1 else: width = w2 if width is None: width = 100 if lines is None: lines = 1 TextEditorWrapped.__init__(self, width, lines, allowed_chars=allowed_chars, **kwds) def format_value(self, x): if x == self.empty: return "" else: return self.format % _(x, doNotTranslate=self.doNotTranslate) def get_text(self): if self.editing: return self._text else: return self.format_value(self.value) def set_text(self, text): if isinstance(text, str): try: text = unicode(text, 'utf-8') except (UnicodeEncodeError, UnicodeDecodeError): print "Failed to convert text to unicode, skipping set text" traceback.print_exc() self.editing = True self._text = _(text, doNotTranslate=self.doNotTranslate) if self.should_commit_immediately(text): self.commit() @staticmethod def should_commit_immediately(text): return False def enter_action(self): if self.editing: self.commit() elif self.enter_passes: return 'pass' def escape_action(self): if self.editing: self.editing = False self.insertion_point = None else: return TextEditorWrapped.escape_action(self) def attention_lost(self): self.commit(notify=True) def clamp_value(self, value): if self.max is not None: value = min(value, self.max) if self.min is not None: value = max(value, self.min) return value def commit(self, notify=False): if self.editing: text = self._text if text: try: value = self.type(text) except ValueError: return value = self.clamp_value(value) else: value = self.empty if value is NotImplemented: return self.value = value self.insertion_point = None if notify: self.change_text(unicode(value)) else: self._text = unicode(value) self.editing = False else: self.insertion_point = None # def get_value(self): # self.commit() # return Control.get_value(self) # # def set_value(self, x): # Control.set_value(self, x) # self.editing = False # --------------------------------------------------------------------------- class TextFieldWrapped(FieldWrapped): type = unicode _value = u""
52,806
34.874321
246
py
MCEdit-Unified
MCEdit-Unified-master/albow/controls.py
# # Albow - Controls # #-# Modified by D.C.-G. for translation purpose from pygame import Rect, draw, transform from pygame.locals import K_RETURN, K_KP_ENTER, K_SPACE from widget import Widget, overridable_property from theme import ThemeProperty import resource from translate import _ class Control(object): highlighted = overridable_property('highlighted') enabled = overridable_property('enabled') value = overridable_property('value') enable = None ref = None _highlighted = False _enabled = True _value = None def get_value(self): ref = self.ref if ref: return ref.get() else: return self._value def set_value(self, x): ref = self.ref if ref: ref.set(x) else: self._value = x def get_highlighted(self): return self._highlighted def get_enabled(self): enable = self.enable if enable: return enable() else: return self._enabled def set_enabled(self, x): self._enabled = x def key_down(self, event): """Handles key press. Captured events are ENTER and SPACE key press. :param event: object: The event being processed.""" key = event.key if key in (K_RETURN, K_KP_ENTER, K_SPACE): self.call_handler("action") else: Widget.key_down(self, event) class AttrRef(object): def __init__(self, obj, attr): self.obj = obj self.attr = attr def get(self): return getattr(self.obj, self.attr) def set(self, x): setattr(self.obj, self.attr, x) class ItemRef(object): def __init__(self, obj, item): self.obj = obj self.item = item def get(self): return self.obj[self.item] def set(self, x): self.obj[self.item] = x class Label(Widget): text = overridable_property('text') align = overridable_property('align') hover_color = ThemeProperty('hover_color') highlight_color = ThemeProperty('highlight_color') disabled_color = ThemeProperty('disabled_color') highlight_bg_color = ThemeProperty('highlight_bg_color') hover_bg_color = ThemeProperty('hover_bg_color') enabled_bg_color = ThemeProperty('enabled_bg_color') disabled_bg_color = ThemeProperty('disabled_bg_color') enabled = True highlighted = False _align = 'l' def __init__(self, text, width=None, base_text=None, **kwds): #-# Translation live update preparation # base_text: to be used each time a widget takes a formated string # defaults to 'text'. Widget.__init__(self, **kwds) #-# Translation live update preparation self.fixed_width = width self.base_text = base_text or text self.previous_translation = _(text, doNotTranslate=kwds.get('doNotTranslate', False)) #-# self._text = _(text, doNotTranslate=kwds.get('doNotTranslate', False)) #-# self.calc_size() #-# #-# Translation live update preparation def calc_size(self): lines = self._text.split("\n") tw, th = 0, 0 for i in xrange(len(lines)): line = lines[i] if i == len(lines) - 1: w, h = self.font.size(line) else: w, h = self.font.size(line)[0], self.font.get_linesize() tw = max(tw, w) th += h if self.fixed_width is not None: tw = self.fixed_width else: tw = max(1, tw) d = 2 * self.margin self.size = (tw + d, th + d) def get_update_translation(self): return Widget.update_translation(self) def set_update_ui(self, v): self.text = self.base_text self.set_text(self.base_text) self.calc_size() Widget.set_update_ui(self, v) #-# def get_text(self): return self._text def set_text(self, x, doNotTranslate=False): self._text = _(x, doNotTranslate=doNotTranslate or self.doNotTranslate) self.calc_size() def get_align(self): return self._align def set_align(self, x): self._align = x def draw(self, surface): if not self.enabled: fg = self.disabled_color bg = self.disabled_bg_color else: fg = self.fg_color bg = self.enabled_bg_color if self.is_default: fg = self.default_choice_color or fg bg = self.default_choice_bg_color or bg if self.is_hover: fg = self.hover_color or fg bg = self.hover_bg_color or bg if self.highlighted: fg = self.highlight_color or fg bg = self.highlight_bg_color or bg self.draw_with(surface, fg, bg) is_default = False def draw_with(self, surface, fg, bg=None): if bg: r = surface.get_rect() b = self.border_width if b: e = -2 * b r.inflate_ip(e, e) surface.fill(bg, r) m = self.margin align = self.align width = surface.get_width() y = m lines = self.text.split("\n") font = self.font dy = font.get_linesize() for line in lines: if len(line): size = font.size(line) if size[0] == 0: continue image = font.render(line, True, fg) r = image.get_rect() r.top = y if align == 'l': r.left = m elif align == 'r': r.right = width - m else: r.centerx = width // 2 surface.blit(image, r) y += dy class GLLabel(Label): pass class SmallLabel(Label): """Small text size. See theme.py""" class ButtonBase(Control): align = 'c' action = None rightClickAction = None default_choice_color = ThemeProperty('default_choice_color') default_choice_bg_color = ThemeProperty('default_choice_bg_color') tab_stop= True def mouse_down(self, event): button = event.button if self.enabled and button == 1: self._highlighted = True def mouse_drag(self, event): state = event in self if event.buttons[0] == 1 and state != self._highlighted: self._highlighted = state self.invalidate() def mouse_up(self, event): button = event.button if event in self and button == 1: if self is event.clicked_widget or (event.clicked_widget and self in event.clicked_widget.all_parents()): self._highlighted = False if self.enabled: self.call_handler('action') if event in self and button == 3 and self.enabled: if self is event.clicked_widget or (event.clicked_widget and self in event.clicked_widget.all_parents()): self.call_handler('rightClickAction') self.get_root().fix_sticky_ctrl() class Button(ButtonBase, Label): def __init__(self, text, action=None, enable=None, rightClickAction=None, **kwds): if action: kwds['action'] = action if enable: kwds['enable'] = enable if rightClickAction: kwds['rightClickAction'] = rightClickAction Label.__init__(self, text, **kwds) class Image(Widget): # image Image to display highlight_color = ThemeProperty('highlight_color') image = overridable_property('image') highlighted = False def __init__(self, image=None, rect=None, prefix="", **kwds): Widget.__init__(self, rect, **kwds) if image: if isinstance(image, basestring): image = resource.get_image(image, prefix=prefix) w, h = image.get_size() d = 2 * self.margin self.size = w + d, h + d self._image = image def get_image(self): return self._image def set_image(self, x): self._image = x def draw(self, surf): frame = surf.get_rect() if self.highlighted: surf.fill(self.highlight_color) image = self.image r = image.get_rect() r.center = frame.center surf.blit(image, r) class RotatableImage(Image): def __init__(self, angle=0.0, min_angle=0, max_angle=360, **kwds): super(RotatableImage, self).__init__(**kwds) self._angle = -angle self._min_angle = min_angle self._max_angle = max_angle def draw(self, surf): frame = surf.get_rect() if self.highlighted: surf.fill(self.highlight_color) image = self.image image = transform.rotate(image, self._angle) r = image.get_rect() r.center = frame.center surf.blit(image, r) def get_angle(self): return self._angle def set_angle(self, angle): angle = max(min(angle, self._max_angle), self._min_angle) self._angle = angle def add_angle(self, angle): self.set_angle(self.get_angle() + (angle * -1)) class ImageButton(ButtonBase, Image): pass class ValueDisplay(Control, Label): format = "%s" align = 'l' def __init__(self, width=100, **kwds): Label.__init__(self, "", **kwds) self.set_size_for_text(width) def get_text(self): return self.format_value(_(self.value, self.doNotTranslate)) def format_value(self, value): if value is not None: return self.format % value else: return "" class SmallValueDisplay(ValueDisplay): pass class ValueButton(ButtonBase, ValueDisplay): align = 'c' def get_text(self): return self.format_value(_(self.value, self.doNotTranslate)) class CheckControl(Control): def mouse_down(self, *args, **kwargs): if self.get_enabled(): self.value = not self.value def get_highlighted(self): return self.value action = mouse_down class CheckWidget(Widget): default_size = (16, 16) margin = 4 border_width = 1 check_mark_tweak = 2 tab_stop = True highlight_color = ThemeProperty('highlight_color') smooth = ThemeProperty('smooth') def __init__(self, **kwds): Widget.__init__(self, Rect((0, 0), self.default_size), **kwds) def draw(self, surf): if self.highlighted: r = self.get_margin_rect() fg = self.fg_color d = self.check_mark_tweak p1 = (r.left, r.centery - d) p2 = (r.centerx - d, r.bottom) p3 = (r.right, r.top - d) if self.smooth: draw.aalines(surf, fg, False, [p1, p2, p3]) else: draw.lines(surf, fg, False, [p1, p2, p3]) class CheckBox(CheckControl, CheckWidget): pass class RadioControl(Control): setting = None def get_highlighted(self): return self.value == self.setting def mouse_down(self, e): self.value = self.setting class RadioButton(RadioControl, CheckWidget): pass
11,333
26.114833
117
py
MCEdit-Unified
MCEdit-Unified-master/albow/text_screen.py
# # Albow - Text Screen # from pygame.locals import * from screen import Screen from theme import FontProperty from resource import get_text from vectors import add, maximum from controls import Button #------------------------------------------------------------------------------ class Page(object): def __init__(self, text_screen, heading, lines): self.text_screen = text_screen self.heading = heading self.lines = lines # width, height = text_screen.heading_font.size(heading) width, height = text_screen.heading_font.size(heading), text_screen.heading_font.get_linesize() for line in lines: # w, h = text_screen.font.size(line) w, h = text_screen.font.size(line)[0], text_screen.font.get_linesize() width = max(width, w) height += h self.size = (width, height) def draw(self, surface, color, pos): heading_font = self.text_screen.heading_font text_font = self.text_screen.font x, y = pos buf = heading_font.render(self.heading, True, color) surface.blit(buf, (x, y)) # y += buf.get_rect().height y += heading_font.get_linesize() for line in self.lines: buf = text_font.render(line, True, color) surface.blit(buf, (x, y)) # y += buf.get_rect().height y += text_font.get_linesize() #------------------------------------------------------------------------------ class TextScreen(Screen): # bg_color = (0, 0, 0) # fg_color = (255, 255, 255) # border = 20 heading_font = FontProperty('heading_font') button_font = FontProperty('button_font') def __init__(self, shell, filename, **kwds): text = get_text(filename) text_pages = text.split("\nPAGE\n") pages = [] page_size = (0, 0) for text_page in text_pages: lines = text_page.strip().split("\n") page = Page(self, lines[0], lines[1:]) pages.append(page) page_size = maximum(page_size, page.size) self.pages = pages bf = self.button_font b1 = Button("Prev Page", font=bf, action=self.prev_page) b2 = Button("Menu", font=bf, action=self.go_back) b3 = Button("Next Page", font=bf, action=self.next_page) b = self.margin page_rect = Rect((b, b), page_size) gap = (0, 18) b1.topleft = add(page_rect.bottomleft, gap) b2.midtop = add(page_rect.midbottom, gap) b3.topright = add(page_rect.bottomright, gap) Screen.__init__(self, shell, **kwds) self.size = add(b3.bottomright, (b, b)) self.add(b1) self.add(b2) self.add(b3) self.prev_button = b1 self.next_button = b3 self.set_current_page(0) def draw(self, surface): b = self.margin self.pages[self.current_page].draw(surface, self.fg_color, (b, b)) def at_first_page(self): return self.current_page == 0 def at_last_page(self): return self.current_page == len(self.pages) - 1 def set_current_page(self, n): self.current_page = n self.prev_button.enabled = not self.at_first_page() self.next_button.enabled = not self.at_last_page() def prev_page(self): if not self.at_first_page(): self.set_current_page(self.current_page - 1) def next_page(self): if not self.at_last_page(): self.set_current_page(self.current_page + 1) def go_back(self): self.parent.show_menu()
3,601
31.745455
103
py
MCEdit-Unified
MCEdit-Unified-master/albow/palette_view.py
from pygame import Rect, draw from grid_view import GridView from utils import frame_rect from theme import ThemeProperty class PaletteView(GridView): # nrows int No. of displayed rows # ncols int No. of displayed columns # # Abstract methods: # # num_items() --> no. of items # draw_item(surface, item_no, rect) # click_item(item_no, event) # item_is_selected(item_no) --> bool sel_width = ThemeProperty('sel_width') zebra_color = ThemeProperty('zebra_color') scroll_button_size = ThemeProperty('scroll_button_size') scroll_button_color = ThemeProperty('scroll_button_color') highlight_style = ThemeProperty('highlight_style') # 'frame' or 'fill' or 'reverse' or None def __init__(self, cell_size, nrows, ncols, scrolling=False, **kwds): GridView.__init__(self, cell_size, nrows, ncols, **kwds) self.scrolling = scrolling if scrolling: d = self.scroll_button_size #l = self.width #b = self.height self.width += d #self.scroll_up_rect = Rect(l, 0, d, d).inflate(-4, -4) #self.scroll_down_rect = Rect(l, b - d, d, d).inflate(-4, -4) self.scroll = 0 self.dragging_hover = False self.scroll_rel = 0 def scroll_up_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.top = m r.right = self.width - m r.inflate_ip(-4, -4) return r def scroll_down_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.bottom = self.height - m r.right = self.width - m r.inflate_ip(-4, -4) return r def draw(self, surface): GridView.draw(self, surface) u = False d = False if self.can_scroll_up(): u = True self.draw_scroll_up_button(surface) if self.can_scroll_down(): d = True self.draw_scroll_down_button(surface) if u or d: self.draw_scrollbar(surface) def draw_scroll_up_button(self, surface): r = self.scroll_up_rect() c = self.scroll_button_color draw.polygon(surface, c, [r.bottomleft, r.midtop, r.bottomright]) def draw_scroll_down_button(self, surface): r = self.scroll_down_rect() c = self.scroll_button_color draw.polygon(surface, c, [r.topleft, r.midbottom, r.topright]) def draw_cell(self, surface, row, col, rect): i = self.cell_to_item_no(row, col) if i is not None: highlight = self.item_is_selected(i) self.draw_item_and_highlight(surface, i, rect, highlight) def draw_item_and_highlight(self, surface, i, rect, highlight): if not i % 2 and "Header" not in str(type(self)): surface.fill(self.zebra_color, rect) if highlight: self.draw_prehighlight(surface, i, rect) if highlight and self.highlight_style == 'reverse': fg = self.inherited('bg_color') or self.sel_color else: fg = self.fg_color self.draw_item_with(surface, i, rect, fg) if highlight: self.draw_posthighlight(surface, i, rect) def draw_item_with(self, surface, i, rect, fg): old_fg = self.fg_color self.fg_color = fg try: self.draw_item(surface, i, rect) finally: self.fg_color = old_fg def draw_prehighlight(self, surface, i, rect): if self.highlight_style == 'reverse': color = self.fg_color else: color = self.sel_color self.draw_prehighlight_with(surface, i, rect, color) def draw_prehighlight_with(self, surface, i, rect, color): style = self.highlight_style if style == 'frame': frame_rect(surface, color, rect, self.sel_width) elif style == 'fill' or style == 'reverse': surface.fill(color, rect) def draw_posthighlight(self, surface, i, rect): pass def mouse_down(self, event): if event.button == 1: if self.scrolling: p = event.local if self.scrollbar_rect().collidepoint(p): self.dragging_hover = True return elif self.scroll_up_rect().collidepoint(p): self.scroll_up() return elif self.scroll_down_rect().collidepoint(p): self.scroll_down() return if event.button == 4: self.scroll_up() if event.button == 5: self.scroll_down() GridView.mouse_down(self, event) def mouse_drag(self, event): if self.dragging_hover: self.scroll_rel += event.rel[1] sub = self.scroll_up_rect().bottom t = self.scroll_down_rect().top d = t - sub # Get the total row number (n). n = self.num_items() / getattr(getattr(self, 'parent', None), 'num_cols', lambda: 1)() # Get the displayed row number (v) s = float(d) / n if abs(self.scroll_rel) >= s: if self.scroll_rel > 0: self.scroll_down(delta=int(abs(self.scroll_rel) / s)) else: self.scroll_up(delta=int(abs(self.scroll_rel) / s)) self.scroll_rel = 0 def mouse_up(self, event): if event.button == 1: if self.dragging_hover: self.dragging_hover = False self.scroll_rel = 0 def scroll_up(self, delta=1): if self.can_scroll_up(): self.scroll -= delta def scroll_down(self, delta=1): if self.can_scroll_down(): self.scroll += delta def scroll_to_item(self, n): i = max(0, min(n, self.num_items() - 1)) p = self.items_per_page() self.scroll = p * (i // p) def can_scroll_up(self): return self.scrolling and self.scroll > 0 def can_scroll_down(self): return self.scrolling and self.scroll + self.items_per_page() < self.num_items() def items_per_page(self): return self.num_rows() * self.num_cols() def click_cell(self, row, col, event): i = self.cell_to_item_no(row, col) if i is not None: self.click_item(i, event) def cell_to_item_no(self, row, col): i = self.scroll + row * self.num_cols() + col if 0 <= i < self.num_items(): return i else: return None def num_rows(self): ch = self.cell_size[1] if ch: return self.height // ch else: return 0 def num_cols(self): width = self.width if self.scrolling: width -= self.scroll_button_size cw = self.cell_size[0] if cw: return width // cw else: return 0 def item_is_selected(self, n): return False def click_item(self, n, e): pass def scrollbar_rect(self): # Get the distance between the scroll buttons (d) sub = self.scroll_up_rect().bottom t = self.scroll_down_rect().top d = t - sub # Get the total row number (n). n = self.num_items() / getattr(getattr(self, 'parent', None), 'num_cols', lambda: 1)() # Get the displayed row number (v) v = self.num_rows() if n: s = float(d) / n else: s = 0 h = s * v if type(h) == float: if h - int(h) > 0: h += 1 top = max(sub, sub + (s * self.scroll) + self.scroll_rel) r = Rect(0, top, self.scroll_button_size, h) m = self.margin r.right = self.width - m r.bottom = min(r.bottom, t) r.inflate_ip(-4, -4) if r.h < 1: r.h = int(h) return r def draw_scrollbar(self, surface): r = self.scrollbar_rect() c = map(lambda x: min(255, max(0, x + 10)), self.scroll_button_color) draw.rect(surface, c, r)
8,223
30.875969
98
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/ChangeMobs.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling from pymclevel import TAG_List from pymclevel import TAG_Byte from pymclevel import TAG_Int from pymclevel import TAG_Float from pymclevel import TAG_Short from pymclevel import TAG_Double from pymclevel import TAG_String displayName = "Change Mob Properties" Professions = { "Farmer (brown)": 0, "Librarian (white)": 1, "Priest (purple)": 2, "Blacksmith (black apron)": 3, "Butcher (white apron)": 4, "Villager (green)": 5, } ProfessionKeys = ("N/A",) for key in Professions.keys(): ProfessionKeys = ProfessionKeys + (key,) noop = -1337 inputs = ( ("Health", noop), ("VelocityX", noop), ("VelocityY", noop), ("VelocityZ", noop), ("Fire", noop), ("FallDistance", noop), ("Air", noop), ("AttackTime", noop), ("HurtTime", noop), ("Lightning Creeper", ("N/A", "Lightning", "No Lightning")), ("Enderman Block Id", noop), ("Enderman Block Data", noop), ("Villager Profession", ProfessionKeys), ("Slime Size", noop), ("Breeding Mode Ticks", noop), ("Child/Adult Age", noop), ) def perform(level, box, options): health = options["Health"] vx = options["VelocityX"] vy = options["VelocityY"] vz = options["VelocityZ"] fire = options["Fire"] fall = options["FallDistance"] air = options["Air"] attackTime = options["AttackTime"] hurtTime = options["HurtTime"] powered = options["Lightning Creeper"] blockId = options["Enderman Block Id"] blockData = options["Enderman Block Data"] profession = options["Villager Profession"] size = options["Slime Size"] breedTicks = options["Breeding Mode Ticks"] age = options["Child/Adult Age"] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: if "Health" in e: if health != noop: e["Health"] = TAG_Short(health) if vx != noop: e["Motion"][0] = TAG_Double(vx) if vy != noop: e["Motion"][1] = TAG_Double(vy) if vz != noop: e["Motion"][2] = TAG_Double(vz) if fire != noop: e["Fire"] = TAG_Short(fire) if fall != noop: e["FallDistance"] = TAG_Float(fall) if air != noop: e["Air"] = TAG_Short(air) if attackTime != noop: e["AttackTime"] = TAG_Short(attackTime) if hurtTime != noop: e["HurtTime"] = TAG_Short(hurtTime) if powered != "N/A" and (e["id"].value == "Creeper" or MCEDIT_IDS.get(e["id"].value) == "DEF_ENTITIES_CREEPER"): if powered == "Lightning": e["powered"] = TAG_Byte(1) if powered == "No Lightning": e["powered"] = TAG_Byte(0) if blockId != noop and (e["id"].value == "Enderman" or MCEDIT_IDS.get(e["id"].value) == "DEF_ENTITIES_ENDERMAN"): e["carried"] = TAG_Short(blockId) if blockData != noop and (e["id"].value == "Enderman" or MCEDIT_IDS.get(e["id"].value) == "DEF_ENTITIES_ENDERMAN"): e["carriedData"] = TAG_Short(blockData) if profession != "N/A" and (e["id"].value == "Villager" or MCEDIT_IDS.get(e["id"].value) == "DEF_ENTITIES_VILLAGER"): e["Profession"] = TAG_Int(Professions[profession]) if size != noop and (e["id"].value == "Slime" or MCEDIT_IDS.get(e["id"].value) == "DEF_ENTITIES_SLIME"): e["Size"] = TAG_Int(size) if breedTicks != noop: e["InLove"] = TAG_Int(breedTicks) if age != noop: e["Age"] = TAG_Int(age) chunk.dirty = True
4,280
33.248
137
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/NBTEdit.py
import ast from pymclevel.box import BoundingBox inputs = [(("Entities", True), ("TileEntities", True), ("TileTicks", True), ("Options", "title")), (("Results", "title"), ("", ["NBTTree", {}, 0, False]), )] tree = None chunks = None boundingBox = None #displayName = "" def set_tree(t): global tree tree = t def nbttree_mouse_down(e): if e.num_clicks > 1: if tree.selected_item and tree.selected_item[3].startswith('(') and tree.selected_item[3].endswith(')'): s = ast.literal_eval(tree.selected_item[3]) editor.mainViewport.cameraPosition = (s[0] + 0.5, s[1] + 2, s[2] - 1) editor.mainViewport.yaw = 0.0 editor.mainViewport.pitch = 45.0 newBox = BoundingBox(s, (1, 1, 1)) editor.selectionTool.setSelection(newBox) tree.treeRow.__class__.mouse_down(tree.treeRow, e) def nbt_ok_action(): if chunks: for chunk in chunks: chunk.dirty = True editor.removeUnsavedEdit() editor.addUnsavedEdit() editor.invalidateBox(boundingBox) def perform(level, box, options): global chunks global boundingBox chunks = [] boundingBox = box data = {"Entities": [], "TileEntities": [], "TileTicks": []} runOn = (options["Entities"], options["TileEntities"], options["TileTicks"]) for (chunk, slices, point) in level.getChunkSlices(box): if runOn[0]: for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x, y, z) in box: data["Entities"].append(e) if chunk not in chunks: chunks.append(chunk) if runOn[1]: for te in chunk.TileEntities: x = te["x"].value y = te["y"].value z = te["z"].value if (x, y, z) in box: data["TileEntities"].append(te) if chunk not in chunks: chunks.append(chunk) if runOn[2]: for tt in chunk.TileTicks: x = tt["x"].value y = tt["y"].value z = tt["z"].value if (x, y, z) in box: data["TileTicks"].append(tt) if chunk not in chunks: chunks.append(chunk) treeData = {"Entities": {}, "TileEntities": {}, "TileTicks": {}} # To set tooltip text to the items the need it, use a dict: {"value": <item to be added to the tree>, "tooltipText": "Some text"} for i in range(len(data["Entities"])): treeData["Entities"][u"%s"%((data["Entities"][i]["Pos"][0].value, data["Entities"][i]["Pos"][1].value, data["Entities"][i]["Pos"][2].value),)] = {"value": data["Entities"][i], "tooltipText": "Double-click to go to this item."} for i in range(len(data["TileEntities"])): treeData["TileEntities"][u"%s"%((data["TileEntities"][i]["x"].value, data["TileEntities"][i]["y"].value, data["TileEntities"][i]["z"].value),)] = {"value": data["TileEntities"][i], "tooltipText": "Double-click to go to this item."} for i in range(len(data["TileTicks"])): treeData["TileTicks"][u"%s"%((data["TileTicks"][i]["x"].value, data["TileTicks"][i]["y"].value, data["TileTicks"][i]["z"].value),)] = {"value": data["TileTicks"][i], "tooltipText": "Double-click to go to this item."} inputs[1][1][1][1] = {'Data': treeData} options[""](inputs[1])
3,622
40.170455
239
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/surfacerepair.py
from numpy import zeros, array import itertools # naturally occuring materials from pymclevel.level import extractHeights blocktypes = [1, 2, 3, 7, 12, 13, 14, 15, 16, 56, 73, 74, 87, 88, 89] blockmask = zeros((256,), dtype='bool') #compute a truth table that we can index to find out whether a block # is naturally occuring and should be considered in a heightmap blockmask[blocktypes] = True displayName = "Chunk Surface Repair" inputs = ( ("Repairs the backwards surfaces made by old versions of Minecraft.", "label"), ) def perform(level, box, options): #iterate through the slices of each chunk in the selection box for chunk, slices, point in level.getChunkSlices(box): # slicing the block array is straightforward. blocks will contain only # the area of interest in this chunk. blocks = chunk.Blocks data = chunk.Data # use indexing to look up whether or not each block in blocks is # naturally-occuring. these blocks will "count" for column height. maskedBlocks = blockmask[blocks] heightmap = extractHeights(maskedBlocks) for x in range(heightmap.shape[0]): for z in range(x + 1, heightmap.shape[1]): h = heightmap[x, z] h2 = heightmap[z, x] if blocks[x, z, h] == 1: h += 2 # rock surface - top 4 layers become 2 air and 2 rock if blocks[z, x, h2] == 1: h2 += 2 # rock surface - top 4 layers become 2 air and 2 rock # topsoil is 4 layers deep def swap(s1, s2): a2 = array(s2) s2[:] = s1[:] s1[:] = a2[:] swap(blocks[x, z, h - 3:h + 1], blocks[z, x, h2 - 3:h2 + 1]) swap(data[x, z, h - 3:h + 1], data[z, x, h2 - 3:h2 + 1]) # remember to do this to make sure the chunk is saved chunk.chunkChanged()
1,963
33.45614
83
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/mcInterface.py
# dummy mcInterface to adapt dudecon's interface to MCEdit's class MCLevelAdapter(object): def __init__(self, level, box): self.level = level self.box = box def check_box_2d(self, x, z): box = self.box if x < box.minx or x >= box.maxx: return False if z < box.minz or z >= box.maxz: return False return True def check_box_3d(self, x, y, z): '''If the coordinates are within the box, return True, else return False''' box = self.box if not self.check_box_2d(x, z): return False if y < box.miny or y >= box.maxy: return False return True def block(self, x, y, z): if not self.check_box_3d(x, y, z): return None d = {'B': self.level.blockAt(x, y, z), 'D': self.level.blockDataAt(x, y, z)} return d def set_block(self, x, y, z, d): if not self.check_box_3d(x, y, z): return None if 'B' in d: self.level.setBlockAt(x, y, z, d['B']) if 'D' in d: self.level.setBlockDataAt(x, y, z, d['D']) def surface_block(self, x, z): if not self.check_box_2d(x, z): return None y = self.level.heightMapAt(x, z) y = max(0, y - 1) d = self.block(x, y, z) if d: d['y'] = y return d SaveFile = MCLevelAdapter #dict['L'] = self.level.blockLightAt(x,y,z) #dict['S'] = self.level.skyLightAt(x,y,z)
1,511
25.526316
84
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/CreateShops.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling # ''' Fixed for MC 1.8 by Rezzing, September 6, 2014 PLEASE READ: The unusable trade won't prevent new trades anymore but I solved it by adding a very high career level. So only use it if you like the fancy stop sign. ''' # Reedited by DragonQuiz, November 8, 2014 # # Changes: ^denotes new change # 1) Allow your villager to move or not. # 2) Rename your villager in MCEdit. # 3) Allow players to receive experience for their trade. # 4) Updated more of the code, made it much prettier. # 5) Added rotation so the villager *can rotate* when possible. # And a big thanks to Sethbling for creating this filter and all his other filters at http://sethbling.com/downloads/mcedit-filters/ from pymclevel import TAG_Byte, TAG_Short, TAG_Int, TAG_Compound, TAG_List, TAG_String, TAG_Double, TAG_Float displayName = "Create Shops" Professions = { "Farmer (brown)": 0, "Librarian (white)": 1, "Priest (purple)": 2, "Blacksmith (black apron)": 3, "Butcher (white apron)": 4, "Villager (green)": 5, } ProfessionKeys = () for key in Professions.keys(): ProfessionKeys += (key,) CustomHeads = { "Skeleton Skull": 0, "Wither Skeleton Skull": 1, "Zombie Skull": 2, "Player Skull": 3, "Creeper Skull": 4 } HeadsKeys = () for key in CustomHeads.keys(): HeadsKeys += (key,) inputs = [(("Trade", "title"), ("This is a modified version of SethBling's Create Shops filter at DragonQuiz's request", "label"), ("Profession", ProfessionKeys), ("Add Stopping Trade", True), ("Invulnerable Villager", True), ("Make Unlimited Trades", True), ("Give Experience per a Trade", True), ("Make Villager not Move", False), ("Make Villager Silent", False), ("Enable Custom Name", True), ("Villager Name", ("string", "width=250")),), (("Rotation", "title"), (" Rotate the Position of your Trader\n" "*Can only be used if Not Move is checked*", "label"), ("Y-Axis", (0, -180, 180)), ("Changes its body rotation. Due west is 0. Must be between -180 to 180 degrees.", "label"), ("X-Axis", (0, -90, 90)), ( "Changes the head rotation Horizontal is 0. Positive values look downward. Must be between -90 to 90 degrees", "label"), ), (("Head", "title"), ("Choose a custom head for the villagers you make", "label"), ("Custom Head", False), ("Legacy Mode (Pre 1.9)", False), ("Skull Type", HeadsKeys), ("", "label"), ("If Player Skull", "label"), ("Player's Name", ("string", "width=250"))), (("Notes", "title"), ("To create a shop first put your buy in the top slot(s) of the chest.\n" "Second put a second buy in the middle slot(optional).\n" "Third put a sell in the bottom slot.\n" "Click the chest you want and choose what you want and click hit enter\n" "*All items must be in the same row*\n" , "label")) ] def perform(level, box, options): # Redefine Professions and CustomHeads with translated data profs = {} global Professions for k, v in Professions.items(): profs[trn._(k)] = v Professions = profs cust_heads = {} global CustomHeads for k, v in CustomHeads.items(): cust_heads[trn._(k)] = v CustomHeads = cust_heads # emptyTrade = options["Add Stopping Trade"] invincible = options["Invulnerable Villager"] unlimited = options["Make Unlimited Trades"] xp = options["Give Experience per a Trade"] nomove = options["Make Villager not Move"] silent = options["Make Villager Silent"] nameVisible = options["Enable Custom Name"] name = options["Villager Name"] yaxis = options["Y-Axis"] xaxis = options["X-Axis"] IsCustomHead = options["Custom Head"] SkullType = options["Skull Type"] legacy = options["Legacy Mode (Pre 1.9)"] PlayerName = options["Player's Name"] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if e["id"].value == "Chest" or MCEDIT_IDS[e["id"].value] == "DEF_TILEENTITIES_CHEST": createShop(level, x, y, z, emptyTrade, invincible, Professions[options["Profession"]], unlimited, xp, nomove, silent, nameVisible, name, yaxis, xaxis, IsCustomHead, legacy, CustomHeads[SkullType], PlayerName) def createShop(level, x, y, z, emptyTrade, invincible, profession, unlimited, xp, nomove, silent, nameVisible, name, yaxis, xaxis, IsCustomHead, legacy, SkullType, PlayerName): chest = level.tileEntityAt(x, y, z) if chest is None: return priceList = {} priceListB = {} saleList = {} for item in chest["Items"]: slot = item["Slot"].value if 0 <= slot <= 8: priceList[slot] = item elif 9 <= slot <= 17: priceListB[slot - 9] = item elif 18 <= slot <= 26: saleList[slot - 18] = item villager = TAG_Compound() villager["PersistenceRequired"] = TAG_Byte(1) villager["OnGround"] = TAG_Byte(1) villager["Air"] = TAG_Short(300) villager["AttackTime"] = TAG_Short(0) villager["DeathTime"] = TAG_Short(0) villager["Fire"] = TAG_Short(-1) villager["Health"] = TAG_Short(20) villager["HurtTime"] = TAG_Short(0) villager["Age"] = TAG_Int(0) villager["Profession"] = TAG_Int(profession) villager["Career"] = TAG_Int(1) villager["CareerLevel"] = TAG_Int(1000) villager["Riches"] = TAG_Int(200) villager["FallDistance"] = TAG_Float(0) villager["Invulnerable"] = TAG_Byte(invincible) villager["NoAI"] = TAG_Byte(nomove) villager["id"] = TAG_String("Villager") villager["Motion"] = TAG_List([TAG_Double(0.0), TAG_Double(0.0), TAG_Double(0.0)]) villager["Pos"] = TAG_List([TAG_Double(x + 0.5), TAG_Double(y), TAG_Double(z + 0.5)]) villager["Rotation"] = TAG_List([TAG_Float(yaxis), TAG_Float(xaxis)]) villager["Willing"] = TAG_Byte(0) villager["Offers"] = TAG_Compound() villager["Offers"]["Recipes"] = TAG_List() if silent: villager["Silent"] = TAG_Byte(1) else: villager["Silent"] = TAG_Byte(0) if nameVisible: villager["CustomName"] = TAG_String(name) villager["CustomNameVisible"] = TAG_Byte(1) else: villager["CustomNameVisible"] = TAG_Byte(0) for i in range(9): if (i in priceList or i in priceListB) and i in saleList: offer = TAG_Compound() if xp: offer["rewardExp"] = TAG_Byte(1) else: offer["rewardExp"] = TAG_Byte(0) if unlimited: offer["uses"] = TAG_Int(0) offer["maxUses"] = TAG_Int(2000000000) else: offer["uses"] = TAG_Int(0) offer["maxUses"] = TAG_Int(1) if i in priceList: offer["buy"] = priceList[i] if i in priceListB: if i in priceList: offer["buyB"] = priceListB[i] else: offer["buy"] = priceListB[i] offer["sell"] = saleList[i] villager["Offers"]["Recipes"].append(offer) if emptyTrade: offer = TAG_Compound() offer["buy"] = TAG_Compound() offer["buy"]["Count"] = TAG_Byte(1) offer["buy"]["Damage"] = TAG_Short(0) offer["buy"]["id"] = TAG_String("minecraft:barrier") offer["sell"] = TAG_Compound() offer["sell"]["Count"] = TAG_Byte(1) offer["sell"]["Damage"] = TAG_Short(0) offer["sell"]["id"] = TAG_String("minecraft:barrier") villager["Offers"]["Recipes"].append(offer) if IsCustomHead: Head = TAG_Compound() Head["id"] = TAG_String("minecraft:skull") Head["Damage"] = TAG_Short(SkullType) Head["Count"] = TAG_Short(1) if SkullType == 3 and PlayerName: Head["tag"] = TAG_Compound() Head["tag"]["SkullOwner"] = TAG_String(PlayerName) if legacy == True: villager["Equipment"] = TAG_List([TAG_Compound(), TAG_Compound(), TAG_Compound(),TAG_Compound(), Head],) else: villager["ArmorItems"] = TAG_List([TAG_Compound(), TAG_Compound(), TAG_Compound(), Head]) level.setBlockAt(x, y, z, 0) chunk = level.getChunk(x / 16, z / 16) chunk.Entities.append(villager) chunk.TileEntities.remove(chest) chunk.dirty = True
8,945
36.120332
176
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/Find.py
# written by texelelf #-# Adding a result pages, and NBT edit stuff from pymclevel import TAG_Byte, TAG_Short, TAG_Int, TAG_Compound, TAG_List, TAG_String, TAG_Double, TAG_Float, TAG_Long, \ TAG_Byte_Array, TAG_Int_Array from pymclevel.box import BoundingBox from albow import alert, ask import ast # Let import the stuff to save files. from mcplatform import askSaveFile from directories import getDocumentsFolder # The RECODR_UNDO is not yet usable... # RECORD_UNDO = False displayName = "Find" tagtypes = {"TAG_Byte": 0, "TAG_Short": 1, "TAG_Int": 2, "TAG_Compound": 3, "TAG_List": 4, "TAG_String": 5, "TAG_Double": 6, "TAG_Float": 7, "TAG_Long": 8, "TAG_Byte_Array": 9, "TAG_Int_Array": 10} tagses = {0: TAG_Byte, 1: TAG_Short, 2: TAG_Int, 3: TAG_Compound, 4: TAG_List, 5: TAG_String, 6: TAG_Double, 7: TAG_Float, 8: TAG_Long, 9: TAG_Byte_Array, 10: TAG_Int_Array, "Any": 11} inputs = [(("Match by:", ("TileEntity", "Entity", "Block")), ("Match block type (for TileEntity searches):", False), ("Match block:", "blocktype"), ("Match block data:", True), ("Match tile entities (for Block searches):", False), ("\"None\" for Name or Value will match any tag's Name or Value respectively.", "label"), ("Match Tag Name:", ("string", "value=None")), ("Match Tag Value:", ("string", "value=None")), ("Case insensitive:", True), ("Match Tag Type:", tuple(("Any",)) + tuple(tagtypes.keys())), ("Operation:", ("Start New Search", "Dump Found Coordinates")), ("Options", "title")), (("Results", "title"), ("", ["NBTTree", {}, 0, False])), # [str name_of_widget_type, dict default_data, int page_to_goback, bool show_load_button] (("Documentation", "title"), ("This filter is designed to search for NBT in either Entities or TileEntities.\n" "It can also be used to search for blocks.\n\"Match by\" determines which type of object " "is prioritized during the search.\nEntites and TileEntities will search relatively quickly, " "while the speed of searching by Block will be directly proportional to the selection size (since every " "single block within the selection will be examined).\n" "All Entity searches will ignore the block settings; TileEntity searches will try to " "\"Match block type\" if checked, and Block searches will try to \"Match tile entity\" tags if " "checked.\nIt is faster to match TileEntity searches with a Block Type than vice versa.\nBlock " "matching can also optionally match block data, e.g. matching all torches, or only torches facing " "a specific direction.\n\"Start New Search\" will re-search through the selected volume, while \"Find Next\" " "will iterate through the search results of the previous search.", "label")) ] tree = None # the tree widget chunks = None # the chunks used to perform the search bbox = None # the bouding box to search in by = None # what is searched: Entities, TileEntities or blocs def set_tree(t): global tree tree = t # Use this method to overwrite the NBT tree default behaviour on mouse clicks def nbttree_mouse_down(e): if e.num_clicks > 1: if tree.selected_item and tree.selected_item[3].startswith('(') and tree.selected_item[3].endswith(')'): s = ast.literal_eval(tree.selected_item[3]) editor.mainViewport.cameraPosition = (s[0] + 0.5, s[1] + 2, s[2] - 1) editor.mainViewport.yaw = 0.0 editor.mainViewport.pitch = 45.0 newBox = BoundingBox(s, (1, 1, 1)) editor.selectionTool.setSelection(newBox) tree.treeRow.__class__.mouse_down(tree.treeRow, e) def get_chunks(): return chunks def get_box(): return bbox def get_by(): return by # Use this method to overwrite the NBT tree 'OK' button default behaviour def nbt_ok_action(): by = get_by() chunks = get_chunks() box = get_box() if by not in (trn._('TileEntity'), trn._('Entity')): return if chunks: for chunk, slices, point in chunks: if by == trn._('TileEntity'): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value elif by == trn._('Entity'): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x, y, z) in box: chunk.dirty = True try: search except NameError: search = None def FindTagS(nbtData, name, value, tagtype): if type(nbtData) is TAG_List or type(nbtData) is TAG_Compound: if name in nbtData.name or name == "": if value == "": if type(nbtData) is tagtype or tagtype == 11: print "found in pre-area" return True if type(nbtData) is TAG_List: list = True else: list = False for tag in range(0, len(nbtData)) if list else nbtData.keys(): if type(nbtData[tag]) is TAG_Compound: if FindTagS(nbtData[tag], name, value, tagtype): return True elif type(nbtData[tag]) is TAG_List: if FindTagS(nbtData[tag], name, value, tagtype): return True else: if name in nbtData[tag].name or name == "": if value in unicode(nbtData[tag].value): if type(nbtData[tag]) is tagtype or tagtype == 11: print "found in list/compound" return True else: return False else: if name in nbtData.name or name == "": if value in unicode(nbtData.value): if type(nbtData[tag]) is tagtype or tagtype == 11: print "found outside" return True return False def FindTagI(nbtData, name, value, tagtype): if type(nbtData) is TAG_List or type(nbtData) is TAG_Compound: if name in (u"%s"%nbtData.name).upper() or name == "": if value == "": if type(nbtData) is tagtype or tagtype == 11: return True if type(nbtData) is TAG_List: list = True else: list = False for tag in range(0, len(nbtData)) if list else nbtData.keys(): if type(nbtData[tag]) is TAG_Compound: if FindTagI(nbtData[tag], name, value, tagtype): return True elif type(nbtData[tag]) is TAG_List: if FindTagI(nbtData[tag], name, value, tagtype): return True else: if name in (u"%s"%nbtData[tag].name).upper() or name == "": if value in unicode(nbtData[tag].value).upper(): if type(nbtData[tag]) is tagtype or tagtype == 11: return True else: return False else: if name in (u"%s"%nbtData.name).upper() or name == "": if value in unicode(nbtData.value).upper(): if type(nbtData[tag]) is tagtype or tagtype == 11: return True return False def FindTag(nbtData, name, value, tagtype, caseSensitive): if caseSensitive: return FindTagS(nbtData, name, value, tagtype) else: return FindTagI(nbtData, name, value, tagtype) def perform(level, box, options): global search # Don't forget to 'globalize' these... global chunks global bbox global by bbox = box by = options["Match by:"] matchtype = options["Match block type (for TileEntity searches):"] matchblock = options["Match block:"] matchdata = options["Match block data:"] matchtile = options["Match tile entities (for Block searches):"] matchname = u"" if options["Match Tag Name:"] == "None" else unicode(options["Match Tag Name:"]) matchval = u"" if options["Match Tag Value:"] == "None" else unicode(options["Match Tag Value:"]) caseSensitive = not options["Case insensitive:"] matchtagtype = tagtypes.get(options["Match Tag Type:"], "Any") op = options["Operation:"] datas = [] if not caseSensitive: matchname = matchname.upper() matchval = matchval.upper() if matchtile and matchname == "" and matchval == "": alert("\nInvalid Tag Name and Value; the present values will match every tag of the specified type.") if search is None or op == trn._("Start New Search") or op == trn._("Dump Found Coordinates"): search = [] if not search: if by == trn._("Block"): for x in xrange(box.minx, box.maxx): for z in xrange(box.minz, box.maxz): for y in xrange(box.miny, box.maxy): block = level.blockAt(x, y, z) data = level.blockDataAt(x, y, z) if block == matchblock.ID and (not matchdata or data == matchblock.blockData): pass else: continue if matchtile: tile = level.tileEntityAt(x, y, z) if tile is not None: if not FindTag(tile, matchname, matchval, tagses[matchtagtype], caseSensitive): continue else: continue search.append((x, y, z)) datas.append(data) elif by == trn._("TileEntity"): chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if matchtype: block = level.blockAt(x, y, z) data = level.blockDataAt(x, y, z) if block == matchblock.ID and (not matchdata or data == matchblock.blockData): pass else: continue if not FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): continue search.append((x, y, z)) datas.append(e) chunks.append([chunk, slices, point]) else: chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x, y, z) in box: if FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): search.append((x, y, z)) datas.append(e) chunks.append([chunk, slices, point]) if not search: alert("\nNo matching blocks/tile entities found") else: search.sort() if op == trn._("Dump Found Coordinates"): result = "\n".join("%d, %d, %d" % pos for pos in search) answer = ask(result, height=editor.height, colLabel="Matching Coordinates", responses=["Save", "OK"]) if answer == "Save": fName = askSaveFile(getDocumentsFolder(), "Save to file...", "find.txt", 'TXT\0*.txt\0\0', 'txt') if fName: fData = "# MCEdit find output\n# Search options:\n# Match by: %s\n# Match block type: %s\n# Match block: %s\n# Match block data: %s\n# Match tile entities: %s\n# Match Tag Name:%s\n# Match Tag Value: %s\n# Case insensitive: %s\n# Match Tag Type: %s\n\n%s"%(by, matchtype, matchblock, matchdata, matchtile, matchname, matchval, caseSensitive, matchtagtype, result) open(fName, 'w').write(fData) else: treeData = {} # To set tooltip text to the items the need it, use a dict: {"value": <item to be added to the tree>, "tooltipText": "Some text"} for i in range(len(search)): if by == trn._('Block'): treeData[u"%s"%(search[i],)] = {"value": datas[i], "tooltipText": "Double-click to go to this item."} elif by == trn._('Entity'): treeData[u"%s"%((datas[i]['Pos'][0].value, datas[i]['Pos'][1].value, datas[i]['Pos'][2].value),)] = {"value": datas[i], "tooltipText": "Double-click to go to this item."} else: treeData[u"%s"%((datas[i]['x'].value, datas[i]['y'].value, datas[i]['z'].value),)] = {"value": datas[i], "tooltipText": "Double-click to go to this item."} inputs[1][1][1][1] = {'Data': treeData} options[""](inputs[1])
13,288
43.89527
383
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/topsoil.py
from numpy import zeros import itertools from pymclevel import alphaMaterials from pymclevel.level import extractHeights am = alphaMaterials # naturally occuring materials blocks = [ am.Grass, am.Dirt, am.Stone, am.Bedrock, am.Sand, am.Gravel, am.GoldOre, am.IronOre, am.CoalOre, am.LapisLazuliOre, am.DiamondOre, am.RedstoneOre, am.RedstoneOreGlowing, am.Netherrack, am.SoulSand, am.Clay, am.Glowstone ] blocktypes = [b.ID for b in blocks] def naturalBlockmask(): blockmask = zeros((256,), dtype='bool') blockmask[blocktypes] = True return blockmask inputs = ( ("Depth", (4, -128, 128)), ("Pick a block:", alphaMaterials.Grass), ("Replace Only:", True), ("", alphaMaterials.Stone) ) def perform(level, box, options): depth = options["Depth"] blocktype = options["Pick a block:"] replace = options["Replace Only:"] replaceType = options[""] #compute a truth table that we can index to find out whether a block # is naturally occuring and should be considered in a heightmap blockmask = naturalBlockmask() # always consider the chosen blocktype to be "naturally occuring" to stop # it from adding extra layers blockmask[blocktype.ID] = True #iterate through the slices of each chunk in the selection box for chunk, slices, point in level.getChunkSlices(box): # slicing the block array is straightforward. blocks will contain only # the area of interest in this chunk. blocks = chunk.Blocks[slices] data = chunk.Data[slices] # use indexing to look up whether or not each block in blocks is # naturally-occuring. these blocks will "count" for column height. maskedBlocks = blockmask[blocks] heightmap = extractHeights(maskedBlocks) for x, z in itertools.product(*map(xrange, heightmap.shape)): h = heightmap[x, z] if depth > 0: if replace: for y in range(max(0, h-depth), h): b, d = blocks[x, z, y], data[x, z, y] if (b == replaceType.ID and d == replaceType.blockData): blocks[x, z, y] = blocktype.ID data[x, z, y] = blocktype.blockData continue blocks[x, z, max(0, h - depth):h] = blocktype.ID data[x, z, max(0, h - depth):h] = blocktype.blockData else: #negative depth values mean to put a layer above the surface if replace: for y in range(h, min(blocks.shape[2], h-depth)): b, d = blocks[x, z, y], data[x, z, y] if (b == replaceType.ID and d == replaceType.blockData): blocks[x, z, y] = blocktype.ID data[x, z, y] = blocktype.blockData blocks[x, z, h:min(blocks.shape[2], h - depth)] = blocktype.ID data[x, z, h:min(blocks.shape[2], h - depth)] = blocktype.blockData #remember to do this to make sure the chunk is saved chunk.chunkChanged()
3,211
31.77551
83
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/MCEditForester.py
'''MCEditForester.py Tree-generating script by dudecon http://www.minecraftforum.net/viewtopic.php?f=1022&t=219461 Needs the dummy mcInterface for MCEdit, and the default Forester script. ''' from pymclevel.materials import alphaMaterials import Forester displayName = "Forester" libraries = [ { "name": "mcInterface", "path": "Bundled Libraries<sep>mcInterface.py", "URL": "None", "optional": False, } ] inputs = ( ("Forester script by dudecon", "label"), ("Shape", ("Procedural", "Normal", "Bamboo", "Palm", "Stickly", "Round", "Cone", "Rainforest", "Mangrove", )), ("Tree Count", 2), ("Tree Height", 35), ("Height Variation", 12), ("Branch Density", 1.0), ("Trunk Thickness", 1.0), ("Broken Trunk", False), ("Hollow Trunk", False), ("Wood", True), ("Foliage", True), ("Foliage Density", 1.0), ("Roots", ("Yes", "To Stone", "Hanging", "No")), ("Root Buttresses", False), ("Wood Material", alphaMaterials.Wood), ("Leaf Material", alphaMaterials.Leaves), ("Plant On", alphaMaterials.Grass), ) def perform(level, box, options): import mcInterface '''Load the file, create the trees, and save the new file. ''' # Set up a reversed translation handler for the Shape and Roots options. reverse_trn = {} for value in (inputs[1][1] + inputs[12][1]): reverse_trn[trn.string_cache.get(value, value)] = value # set up the non 1 to 1 mappings of options to Forester global names optmap = { "Tree Height": "CENTERHEIGHT", } # automatically set the options that map 1 to 1 from options to Forester def setOption(opt): OPT = optmap.get(opt, opt.replace(" ", "").upper()) if OPT in dir(Forester): val = reverse_trn.get(options[opt], options[opt]) if isinstance(val, (str, unicode)): val = val.replace(" ", "").lower() setattr(Forester, OPT, val) # set all of the options for option in options: setOption(option) # set the EDGEHEIGHT the same as CENTERHEIGHT Forester.EDGEHEIGHT = Forester.CENTERHEIGHT # set the materials wood = options["Wood Material"] leaf = options["Leaf Material"] grass = options["Plant On"] Forester.WOODINFO = {"B": wood.ID, "D": wood.blockData} Forester.LEAFINFO = {"B": leaf.ID, "D": leaf.blockData} Forester.PLANTON = [grass.ID] # calculate the plant-on center and radius x_center = int(box.minx + (box.width / 2)) z_center = int(box.minz + (box.length / 2)) edge_padding = int(Forester.EDGEHEIGHT * 0.618) max_dim = min(box.width, box.length) planting_radius = (max_dim / 2) - edge_padding if planting_radius <= 1: planting_radius = 1 Forester.TREECOUNT = 1 print("Box isn't wide and/or long enough. Only planting one tree.") # set the position to plant Forester.X = x_center Forester.Z = z_center Forester.RADIUS = planting_radius print("Plant radius = " + str(planting_radius)) # set the Forester settings that are not in the inputs # and should be a specific value # take these out if added to settings Forester.LIGHTINGFIX = False Forester.MAXTRIES = 5000 Forester.VERBOSE = True # create the dummy map object mcmap = mcInterface.MCLevelAdapter(level, box) # call forester's main function on the map object. Forester.main(mcmap) level.markDirtyBox(box)
3,683
28.709677
76
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/BanSlimes.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling from pymclevel import TAG_Long # This mimics some of the functionality from the Java Random class. # Java Random source code can be found here: http://developer.classpath.org/doc/java/util/Random-source.html class Random: def __init__(self, randseed): self.setSeed(randseed) def setSeed(self, randseed): self.randseed = (randseed ^ 0x5DEECE66DL) & ((1L << 48) - 1) def next(self, bits): self.randseed = long(self.randseed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1) return int(self.randseed >> (48 - bits)) def nextInt(self, n): while True: bits = self.next(31) val = bits % n if int(bits - val + (n - 1)) >= 0: break return val # Algorithm found here: http://www.minecraftforum.net/topic/397835-find-slime-spawning-chunks-125/ def slimeChunk(seed, x, z): randseed = long(seed) + long(x * x * 0x4c1906) + long(x * 0x5ac0db) + long(z * z) * 0x4307a7L + long( z * 0x5f24f) ^ 0x3ad8025f r = Random(randseed) i = r.nextInt(10) return i == 0 def goodSeed(box, seed): minx = int(box.minx / 16) * 16 minz = int(box.minz / 16) * 16 for x in xrange(minx, box.maxx, 16): for z in xrange(minz, box.maxz, 16): if slimeChunk(seed, x, z): return False return True inputs = ( ("Max Seed", 100000), ) def perform(level, box, options): for seed in xrange(options["Max Seed"]): if goodSeed(box, long(seed)): level.root_tag["Data"]["RandomSeed"] = TAG_Long(seed) print "Found good seed: " + str(seed) return print "Didn't find good seed."
1,817
26.969231
108
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/AddPotionEffect.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling from pymclevel import TAG_List from pymclevel import TAG_Byte from pymclevel import TAG_Int from pymclevel import TAG_Compound displayName = "Add Potion Effect to Mobs" Effects = { "Speed": 1, "Slowness": 2, "Strength": 5, "Jump Boost": 8, "Regeneration": 10, "Resistance": 11, "Fire Resistance": 12, "Water Breathing": 13, "Invisibility": 14, "Weakness": 18, "Poison": 19, "Wither": 20, "Health Boost": 21, "Absorption": 22, "Haste (no mob effect)": 3, "Mining Fatigue (no mob effect)": 4, "Nausea (no mob effect)": 9, "Blindness (no mob effect)": 15, "Hunger (no mob effect)": 17, "Night Vision (no mob effect)": 16, "Saturation (no mob effect)": 23, } EffectKeys = () for key in Effects.keys(): EffectKeys = EffectKeys + (key,) inputs = ( ("Effect", EffectKeys), ("Level", 1), ("Duration (Seconds)", 60), ) def perform(level, box, options): effect = dict([(trn._(a), b) for a, b in Effects.items()])[options["Effect"]] amp = options["Level"] duration = options["Duration (Seconds)"] * 20 for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: if trn._("Health") in e: if "ActiveEffects" not in e: e["ActiveEffects"] = TAG_List() ef = TAG_Compound() ef["Amplifier"] = TAG_Byte(amp) ef["Id"] = TAG_Byte(effect) ef["Duration"] = TAG_Int(duration) e["ActiveEffects"].append(ef) chunk.dirty = True
1,879
26.246377
98
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/floodwater.py
from numpy import * from pymclevel import alphaMaterials, faceDirections, FaceYIncreasing from collections import deque import datetime displayName = "Classic Water Flood" inputs = ( ( "Makes water in the region flood outwards and downwards, becoming full source blocks in the process. This is similar to Minecraft Classic water.", "label"), ("Flood Water", True), ("Flood Lava", False), ) def perform(level, box, options): def floodFluid(waterIDs, waterID): waterTable = zeros(256, dtype='bool') waterTable[waterIDs] = True coords = [] for chunk, slices, point in level.getChunkSlices(box): water = waterTable[chunk.Blocks[slices]] chunk.Data[slices][water] = 0 # source block x, z, y = water.nonzero() x = x + (point[0] + box.minx) z = z + (point[2] + box.minz) y = y + (point[1] + box.miny) coords.append(transpose((x, y, z))) print "Stacking coords..." coords = vstack(tuple(coords)) def processCoords(coords): newcoords = deque() for (x, y, z) in coords: for _dir, offsets in faceDirections: if _dir == FaceYIncreasing: continue dx, dy, dz = offsets p = (x + dx, y + dy, z + dz) if p not in box: continue nx, ny, nz = p if level.blockAt(nx, ny, nz) == 0: level.setBlockAt(nx, ny, nz, waterID) newcoords.append(p) return newcoords def spread(coords): while len(coords): start = datetime.datetime.now() num = len(coords) print "Did {0} coords in ".format(num), coords = processCoords(coords) d = datetime.datetime.now() - start print d yield "Did {0} coords in {1}".format(num, d) level.showProgress("Spreading water...", spread(coords), cancel=True) if options["Flood Water"]: waterIDs = [alphaMaterials.WaterActive.ID, alphaMaterials.Water.ID] waterID = alphaMaterials.Water.ID floodFluid(waterIDs, waterID) if options["Flood Lava"]: lavaIDs = [alphaMaterials.LavaActive.ID, alphaMaterials.Lava.ID] lavaID = alphaMaterials.Lava.ID floodFluid(lavaIDs, lavaID)
2,508
32.013158
150
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/Invincible.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling from pymclevel import TAG_List from pymclevel import TAG_Byte from pymclevel import TAG_Int from pymclevel import TAG_Compound displayName = "Make Mobs Invincible" def perform(level, box, options): for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: if "Health" in e: if "ActiveEffects" not in e: e["ActiveEffects"] = TAG_List() resist = TAG_Compound() resist["Amplifier"] = TAG_Byte(4) resist["Id"] = TAG_Byte(11) resist["Duration"] = TAG_Int(2000000000) e["ActiveEffects"].append(resist) chunk.dirty = True
1,075
33.709677
98
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/decliff.py
""" DeCliff filter contributed by Minecraft Forums user "DrRomz" Originally posted here: http://www.minecraftforum.net/topic/13807-mcedit-minecraft-world-editor-compatible-with-mc-beta-18/page__st__3940__p__7648793#entry7648793 """ from numpy import zeros, array import itertools from pymclevel import alphaMaterials am = alphaMaterials # Consider below materials when determining terrain height blocks = [ am.Stone, am.Grass, am.Dirt, am.Bedrock, am.Sand, am.Sandstone, am.Clay, am.Gravel, am.GoldOre, am.IronOre, am.CoalOre, am.LapisLazuliOre, am.DiamondOre, am.RedstoneOre, am.RedstoneOreGlowing, am.Netherrack, am.SoulSand, am.Glowstone ] terrainBlocktypes = [b.ID for b in blocks] terrainBlockmask = zeros((256,), dtype='bool') # Truth table used to calculate terrain height # trees, leaves, etc. sit on top of terrain terrainBlockmask[terrainBlocktypes] = True inputs = ( # Option to limit change to raise_cliff_floor / lower_cliff_top # Default is to adjust both and meet somewhere in the middle ("Raise/Lower", ("Both", "Lower Only", "Raise Only")), ) # # Calculate the maximum adjustment that can be made from # cliff_pos in direction dir (-1/1) keeping terain at most # maxstep blocks away from previous column def maxadj(heightmap, slice_no, cliff_pos, dir, pushup, maxstep, slice_width): ret = 0 if dir < 0: if cliff_pos < 2: return 0 end = 0 else: if cliff_pos > slice_width - 2: return 0 end = slice_width - 1 for cur_pos in range(cliff_pos, end, dir): if pushup: ret = ret + \ max([0, maxstep - dir * heightmap[slice_no, cur_pos] + dir * heightmap[slice_no, cur_pos + dir]]) else: ret = ret + \ min([0, -maxstep + dir * heightmap[slice_no, cur_pos] - dir * heightmap[slice_no, cur_pos + dir]]) return ret # # Raise/lower column at cliff face by adj and decrement change as we move away # from the face. Each level will be at most maxstep blocks from those beside it. # # This function dosn't actually change anything, but just sets array 'new' # with the desired height. def adjheight(orig, new, slice_no, cliff_pos, dir, adj, can_adj, maxstep, slice_width): cur_adj = adj prev = 0 done_adj = 0 if dir < 0: end = 1 else: end = slice_width - 1 if adj == 0 or can_adj == 0: for cur_pos in range(cliff_pos, end, dir): new[slice_no, cur_pos] = orig[slice_no, cur_pos] else: for cur_pos in range(cliff_pos, end, dir): if adj > 0: done_adj = done_adj + \ max([0, maxstep - orig[slice_no, cur_pos] + orig[slice_no, cur_pos + dir]]) if orig[slice_no, cur_pos] - \ orig[slice_no, cur_pos + dir] > 0: cur_adj = max([0, cur_adj - orig[slice_no, cur_pos] + orig[slice_no, cur_pos + dir]]) prev = adj - cur_adj else: done_adj = done_adj + \ min([0, -maxstep + orig[slice_no, cur_pos] - orig[slice_no, cur_pos + dir]]) if orig[slice_no, cur_pos] - \ orig[slice_no, cur_pos + dir] > 0: cur_adj = min([0, cur_adj + orig[slice_no, cur_pos] - orig[slice_no, cur_pos + dir]]) prev = adj - cur_adj new[slice_no, cur_pos] = max([0, orig[slice_no, cur_pos] + cur_adj]) if cur_adj != 0 and \ abs(prev) < abs(int(adj * done_adj / can_adj)): cur_adj += prev - int(adj * done_adj / can_adj) prev = int(adj * done_adj / can_adj) new[slice_no, end] = orig[slice_no, end] def perform(level, box, options): if box.volume > 16000000: raise ValueError("Volume too big for this filter method!") RLOption = options["Raise/Lower"] schema = level.extractSchematic(box) schema.removeEntitiesInBox(schema.bounds) schema.removeTileEntitiesInBox(schema.bounds) terrainBlocks = terrainBlockmask[schema.Blocks] coords = terrainBlocks.nonzero() # Swap values around so long edge of selected rectangle is first # - the long edge is assumed to run parallel to the cliff face # and we want to process slices perpendicular to the face # heightmap will have x,z (or z,x) index with highest ground level if schema.Width > schema.Length: heightmap = zeros((schema.Width, schema.Length), dtype='float32') heightmap[coords[0], coords[1]] = coords[2] newHeightmap = zeros((schema.Width, schema.Length), dtype='uint16') slice_count = schema.Width slice_width = schema.Length else: heightmap = zeros((schema.Length, schema.Width), dtype='float32') heightmap[coords[1], coords[0]] = coords[2] newHeightmap = zeros((schema.Length, schema.Width), dtype='uint16') slice_count = schema.Length slice_width = schema.Width nonTerrainBlocks = ~terrainBlocks nonTerrainBlocks &= schema.Blocks != 0 for slice_no in range(0, slice_count): cliff_height = 0 # determine pos and height of cliff in this slice for cur_pos in range(0, slice_width - 1): if abs(heightmap[slice_no, cur_pos] - heightmap[slice_no, cur_pos + 1]) > abs(cliff_height): cliff_height = \ heightmap[slice_no, cur_pos] - \ heightmap[slice_no, cur_pos + 1] cliff_pos = cur_pos if abs(cliff_height) < 2: # nothing to adjust - just copy heightmap to newHightmap adjheight(heightmap, newHeightmap, slice_no, 0, 1, 0, 1, 1, slice_width) continue # Try to keep adjusted columns within 1 column of their neighbours # but ramp up to 4 blocks up/down on each column when needed for max_step in range(1, 4): can_left = maxadj(heightmap, slice_no, cliff_pos, -1, cliff_height < 0, max_step, slice_width) can_right = maxadj(heightmap, slice_no, cliff_pos + 1, 1, cliff_height > 0, max_step, slice_width) if can_right < 0 and RLOption == "Raise Only": can_right = 0 if can_right > 0 and RLOption == "Lower Only": can_right = 0 if can_left < 0 and RLOption == "Raise Only": can_left = 0 if can_left > 0 and RLOption == "Lower Only": can_left = 0 if 0 > cliff_height > can_right - can_left: if abs(can_left) > abs(can_right): adj_left = -1 * (cliff_height - max([int(cliff_height / 2), can_right])) adj_right = cliff_height + adj_left else: adj_right = cliff_height - max([int(cliff_height / 2), -can_left]) adj_left = -1 * (cliff_height - adj_right + 1) else: if 0 < cliff_height < can_right - can_left: if abs(can_left) > abs(can_right): adj_left = -1 * (cliff_height - min([int(cliff_height / 2), can_right])) adj_right = cliff_height + adj_left else: adj_right = cliff_height - min([int(cliff_height / 2), -can_left]) - 1 adj_left = -1 * (cliff_height - adj_right) else: adj_right = 0 adj_left = 0 continue break adjheight(heightmap, newHeightmap, slice_no, cliff_pos, -1, adj_left, can_left, max_step, slice_width) adjheight(heightmap, newHeightmap, slice_no, cliff_pos + 1, 1, adj_right, can_right, max_step, slice_width) # OK, newHeightMap has new height for each column # so it's just a matter of moving everything up/down for x, z in itertools.product(xrange(1, schema.Width - 1), xrange(1, schema.Length - 1)): if schema.Width > schema.Length: oh = heightmap[x, z] nh = newHeightmap[x, z] else: oh = heightmap[z, x] nh = newHeightmap[z, x] delta = nh - oh column = array(schema.Blocks[x, z]) # Keep bottom 5 blocks, so we don't loose bedrock keep = min([5, nh]) Waterdepth = 0 # Detect Water on top if column[oh + 1:oh + 2] == am.Water.ID or \ column[oh + 1:oh + 2] == am.Ice.ID: for cur_pos in range(int(oh) + 1, schema.Height): if column[cur_pos:cur_pos + 1] != am.Water.ID and \ column[cur_pos:cur_pos + 1] != am.Ice.ID: break Waterdepth += 1 if delta == 0: column[oh:] = schema.Blocks[x, z, oh:] if delta < 0: # Moving column down column[keep:delta] = schema.Blocks[x, z, keep - delta:] column[delta:] = am.Air.ID if Waterdepth > 0: # Avoid steping small lakes, etc on cliff top # replace with dirt 'n grass column[nh:nh + 1] = am.Grass.ID column[nh + 1:nh + 1 + delta] = am.Air.ID if delta > 0: # Moving column up column[keep + delta:] = schema.Blocks[x, z, keep:-delta] # Put stone in gap at the bottom column[keep:keep + delta] = am.Stone.ID if Waterdepth > 0: if Waterdepth > delta: # Retain Ice if column[nh + Waterdepth:nh + Waterdepth + 1] == am.Ice.ID: column[nh + Waterdepth - delta:nh + 1 + Waterdepth - delta] = \ am.Ice.ID column[nh + 1 + Waterdepth - delta:nh + 1 + Waterdepth] = am.Air.ID else: if Waterdepth < delta - 2: column[nh:nh + 1] = am.Grass.ID column[nh + 1:nh + 1 + Waterdepth] = am.Air.ID else: # Beach at the edge column[nh - 4:nh - 2] = am.Sandstone.ID column[nh - 2:nh + 1] = am.Sand.ID column[nh + 1:nh + 1 + Waterdepth] = am.Air.ID schema.Blocks[x, z] = column level.copyBlocksFrom(schema, schema.bounds, box.origin)
10,724
37.16726
138
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/CreateBusses.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling from numpy import sign displayName = "Create Busses" def perform(level, box, options): level.markDirtyBox(box) bus = BusCreator(level, box, options) bus.getTerminals() bus.getGuides() bus.pickAllPaths() bus.createAllBusses() HorizDirs = [ (1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1), ] Down = (0, -1, 0) Up = (0, 1, 0) def getHorizDir((x1, y1, z1), (x2, y2, z2)): if abs(x2 - x1) > abs(z2 - z1): return sign(x2 - x1), 0, 0 else: if z2 == z1: return 1, 0, 0 else: return 0, 0, sign(z2 - z1) def getSecondaryDir((x1, y1, z1), (x2, y2, z2)): if abs(x2 - x1) > abs(z2 - z1): return 0, 0, sign(z2 - z1) else: return sign(x2 - x1), 0, 0 def leftOf((dx1, dy1, dz1), (dx2, dy2, dz2)): return dx1 == dz2 or dz1 == dx2 * -1 def rotateRight((dx, dy, dz)): return -dz, dy, dx def rotateLeft((dx, dy, dz)): return dz, dy, -dx def allAdjacentSamePlane(dir, secondaryDir): right = rotateRight(dir) left = rotateLeft(dir) back = rotateRight(right) if leftOf(secondaryDir, dir): return ( dir, left, right, getDir(dir, Up), getDir(dir, Down), getDir(left, Up), getDir(right, Up), getDir(left, Down), getDir(right, Down), back, getDir(back, Up), getDir(back, Down), ) else: return ( dir, right, left, getDir(dir, Up), getDir(dir, Down), getDir(right, Up), getDir(left, Up), getDir(right, Down), getDir(left, Down), back, getDir(back, Up), getDir(back, Down), ) def allAdjacentUp(dir, secondaryDir): right = rotateRight(dir) left = rotateLeft(dir) back = rotateRight(right) if leftOf(secondaryDir, dir): return ( getDir(dir, Up), getDir(left, Up), getDir(right, Up), getDir(back, Up), dir, left, right, back, getDir(dir, Down), getDir(left, Down), getDir(right, Down), getDir(back, Down), ) else: return ( getDir(dir, Up), getDir(right, Up), getDir(left, Up), getDir(back, Up), dir, right, left, back, getDir(dir, Down), getDir(right, Down), getDir(left, Down), getDir(back, Down), ) def allAdjacentDown(dir, secondaryDir): right = rotateRight(dir) left = rotateLeft(dir) back = rotateRight(right) if leftOf(secondaryDir, dir): return ( getDir(dir, Down), getDir(left, Down), getDir(right, Down), getDir(back, Down), dir, left, right, back, getDir(dir, Up), getDir(left, Up), getDir(right, Up), getDir(back, Up), ) else: return ( getDir(dir, Down), getDir(right, Down), getDir(left, Down), getDir(back, Down), dir, right, left, back, getDir(dir, Up), getDir(right, Up), getDir(left, Up), getDir(back, Up), ) def getDir((x, y, z), (dx, dy, dz)): return x + dx, y + dy, z + dz def dist((x1, y1, z1), (x2, y2, z2)): return abs(x2 - x1) + abs(y2 - y1) + abs(z2 - z1) def above((x1, y1, z1), (x2, y2, z2)): return y1 > y2 def below((x1, y1, z1), (x2, y2, z2)): return y1 < y2 def insideBox(box, (x, y, z)): return box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz Colors = { 0: "white", 1: "orange", 2: "magenta", 3: "light blue", 4: "yellow", 5: "lime green", 6: "pink", 7: "gray", 8: "light gray", 9: "cyan", 10: "purple", 11: "blue", 12: "brown", 13: "green", 14: "red", 15: "black", } class BusCreator: starts = {} ends = {} guides = {} path = {} def __init__(self, level, box, options): self.level = level self.box = box self.options = options def getTerminals(self): for x in xrange(self.box.minx, self.box.maxx): for y in xrange(self.box.miny, self.box.maxy): for z in xrange(self.box.minz, self.box.maxz): (color, start) = self.isTerminal((x, y, z)) if color is not None and start is not None: if start: if color in self.starts: raise Exception("Duplicate starting point for " + Colors[color] + " bus") self.starts[color] = (x, y, z) else: if color in self.ends: raise Exception("Duplicate ending point for " + Colors[color] + " bus") self.ends[color] = (x, y, z) def getGuides(self): for x in xrange(self.box.minx, self.box.maxx): for y in xrange(self.box.miny, self.box.maxy): for z in xrange(self.box.minz, self.box.maxz): pos = (x, y, z) if self.getBlockAt(pos) == 35: color = self.getBlockDataAt(pos) if color not in self.starts or color not in self.ends: continue if color not in self.guides: self.guides[color] = [] rs = getDir(pos, Up) if rs == self.starts[color] or rs == self.ends[color]: continue self.guides[color].append(rs) def isTerminal(self, (x, y, z)): pos = (x, y, z) for dir in HorizDirs: otherPos = getDir(pos, dir) towards = self.repeaterPointingTowards(pos, otherPos) away = self.repeaterPointingAway(pos, otherPos) if not (away or towards): # it's not a repeater pointing towards or away continue if self.getBlockAt(otherPos) != 55: # the other block isn't redstone continue if self.getBlockAt(getDir(pos, Down)) != 35: # it's not sitting on wool continue if self.getBlockAt(getDir(otherPos, Down)) != 35: # the other block isn't sitting on wool continue data = self.getBlockDataAt(getDir(pos, Down)) if self.getBlockDataAt(getDir(otherPos, Down)) != data: # the wool colors don't match continue return data, towards return None, None def pickAllPaths(self): for color in range(0, 16): if color in self.starts and color in self.ends: self.pickPath(color) def pickPath(self, color): self.path[color] = () currentPos = self.starts[color] while True: minDist = None minGuide = None for guide in self.guides[color]: guideDist = dist(currentPos, guide) if minDist is None or guideDist < minDist: minDist = guideDist minGuide = guide if dist(currentPos, self.ends[color]) == 1: return if minGuide is None: return self.path[color] = self.path[color] + (minGuide,) currentPos = minGuide self.guides[color].remove(minGuide) def createAllBusses(self): for color in range(0, 16): if color in self.path: self.connectDots(color) def connectDots(self, color): prevGuide = None self.power = 1 for guide in self.path[color]: if prevGuide is not None: self.createConnection(prevGuide, guide, color) prevGuide = guide def createConnection(self, pos1, pos2, color): currentPos = pos1 while currentPos != pos2: self.power += 1 hdir = getHorizDir(currentPos, pos2) secondaryDir = getSecondaryDir(currentPos, pos2) if above(currentPos, pos2): dirs = allAdjacentDown(hdir, secondaryDir) elif below(currentPos, pos2): dirs = allAdjacentUp(hdir, secondaryDir) else: dirs = allAdjacentSamePlane(hdir, secondaryDir) if self.power == 1: restrictions = 2 elif self.power == 15: restrictions = 1 else: restrictions = 0 placed = False for dir in dirs: pos = getDir(currentPos, dir) if self.canPlaceRedstone(pos, currentPos, pos2, restrictions): if self.power == 15: self.placeRepeater(pos, dir, color) self.power = 0 else: self.placeRedstone(pos, color) currentPos = pos placed = True break if not placed: # raise Exception("Algorithm failed to create bus for " + Colors[color] + " wire.") return def canPlaceRedstone(self, pos, fromPos, destinationPos, restrictions): if restrictions == 1 and above(pos, fromPos): # repeater return False if restrictions == 2 and below(pos, fromPos): # just after repeater return False if restrictions == 2 and not self.repeaterPointingTowards(fromPos, pos): # just after repeater return False if above(pos, fromPos) and self.getBlockAt(getDir(getDir(pos, Down), Down)) == 55: return False if below(pos, fromPos) and self.getBlockAt(getDir(pos, Up)) != 0: return False if getDir(pos, Down) == destinationPos: return False if pos == destinationPos: return True if self.getBlockAt(pos) != 0: return False if self.getBlockAt(getDir(pos, Down)) != 0: return False if not insideBox(self.box, pos): return False for dir in allAdjacentSamePlane((1, 0, 0), (0, 0, 0)): testPos = getDir(pos, dir) if testPos == fromPos or testPos == getDir(fromPos, Down): continue if testPos == destinationPos or testPos == getDir(destinationPos, Down): continue blockid = self.getBlockAt(testPos) if blockid != 0: return False return True def placeRedstone(self, pos, color): self.setBlockAt(pos, 55) # redstone self.setBlockAt(getDir(pos, Down), 35, color) # wool def placeRepeater(self, pos, (dx, dy, dz), color): if dz == -1: self.setBlockAt(pos, 93, 0) # north elif dx == 1: self.setBlockAt(pos, 93, 1) # east elif dz == 1: self.setBlockAt(pos, 93, 2) # south elif dx == -1: self.setBlockAt(pos, 93, 3) # west self.setBlockAt(getDir(pos, Down), 35, color) # wool def getBlockAt(self, (x, y, z)): return self.level.blockAt(x, y, z) def getBlockDataAt(self, (x, y, z)): return self.level.blockDataAt(x, y, z) def setBlockAt(self, (x, y, z), id, dmg=0): self.level.setBlockAt(x, y, z, id) self.level.setBlockDataAt(x, y, z, dmg) def repeaterPointingTowards(self, (x1, y1, z1), (x2, y2, z2)): blockid = self.getBlockAt((x1, y1, z1)) if blockid != 93 and blockid != 94: return False direction = self.level.blockDataAt(x1, y1, z1) % 4 if direction == 0 and z2 - z1 == -1: return True if direction == 1 and x2 - x1 == 1: return True if direction == 2 and z2 - z1 == 1: return True if direction == 3 and x2 - x1 == -1: return True return False def repeaterPointingAway(self, (x1, y1, z1), (x2, y2, z2)): blockid = self.getBlockAt((x1, y1, z1)) if blockid != 93 and blockid != 94: return False direction = self.level.blockDataAt(x1, y1, z1) % 4 if direction == 0 and z2 - z1 == 1: return True if direction == 1 and x2 - x1 == -1: return True if direction == 2 and z2 - z1 == -1: return True if direction == 3 and x2 - x1 == 1: return True return False
12,797
26.229787
105
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/smoothshape.py
# Enlarge Filter by SethBling # Feel free to modify and reuse, but credit to SethBling would be nice. # http://youtube.com/sethbling from numpy import zeros inputs = ( ("Smoothing", (1, 1, 20)), ("Made by Sethbling", "label") ) displayName = "Smooth - 3D" def perform(level, box, options): smoothing = options["Smoothing"] width = box.maxx - box.minx height = box.maxy - box.miny depth = box.maxz - box.minz blocks = zeros((width, height, depth)) dmgs = zeros((width, height, depth)) cache = {} for dx in xrange(width): for dy in xrange(height): for dz in xrange(depth): x = box.minx + dx y = box.miny + dy z = box.minz + dz (block, dmg) = getSmoothed(level, x, y, z, smoothing, cache) blocks[dx, dy, dz] = block dmgs[dx, dy, dz] = dmg for dx in xrange(width): for dy in xrange(height): for dz in xrange(depth): x = box.minx + dx y = box.miny + dy z = box.minz + dz level.setBlockAt(x, y, z, blocks[dx, dy, dz]) level.setBlockDataAt(x, y, z, dmgs[dx, dy, dz]) level.markDirtyBox(box) def getSmoothed(level, x, y, z, smoothing, cache): counts = {} for dx in xrange(-smoothing, smoothing): for dy in xrange(-smoothing, smoothing): for dz in xrange(-smoothing, smoothing): if dx*dx + dy*dy + dz*dz > smoothing*smoothing: continue cx = x + dx cy = y + dy cz = z + dz block = 0 dmg = 0 if not (cx, cy, cz) in cache: block = level.blockAt(cx, cy, cz) dmg = level.blockDataAt(cx, cy, cz) cache[(cx, cy, cz)] = (block, dmg) else: (block, dmg) = cache[(cx, cy, cz)] if not (block, dmg) in counts: counts[(block, dmg)] = 0 counts[(block, dmg)] = counts[(block, dmg)] + 1 maxcount = 0 maxbl = (0, 0) for (bl, count) in counts.iteritems(): if count > maxcount: maxcount = count maxbl = bl return maxbl
2,350
25.715909
76
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/CreateSpawners.py
# Feel free to modify and use this filter however you wish. If you do, # please give credit to SethBling. # http://youtube.com/SethBling from pymclevel import TAG_Compound from pymclevel import TAG_Int from pymclevel import TAG_Short from pymclevel import TAG_Byte from pymclevel import TAG_String from pymclevel import TAG_Float from pymclevel import TAG_Double from pymclevel import TAG_List from pymclevel import TileEntity from copy import deepcopy displayName = "Create Spawners" inputs = ( ("Include position data", False), ) def perform(level, box, options): includePos = options["Include position data"] entitiesToRemove = [] for (chunk, slices, point) in level.getChunkSlices(box): for _entity in chunk.Entities: entity = deepcopy(_entity) x = int(entity["Pos"][0].value) y = int(entity["Pos"][1].value) z = int(entity["Pos"][2].value) if box.minx <= x < box.maxx and box.miny <= y < box.maxy and box.minz <= z < box.maxz: entitiesToRemove.append((chunk, _entity)) level.setBlockAt(x, y, z, 52) level.setBlockDataAt(x, y, z, 0) spawner = TileEntity.Create("MobSpawner", entity=entity) TileEntity.setpos(spawner, (x, y, z)) spawner["Delay"] = TAG_Short(120) if not includePos: del spawner["SpawnData"]["Pos"] spawner["EntityId"] = entity["id"] chunk.TileEntities.append(spawner) for (chunk, entity) in entitiesToRemove: chunk.Entities.remove(entity)
1,626
30.288462
98
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/setbiome.py
# SethBling's SetBiome Filter # Directions: Just select a region and use this filter, it will apply the # biome to all columns within the selected region. It can be used on regions # of any size, they need not correspond to chunks. # # If you modify and redistribute this code, please credit SethBling from pymclevel import MCSchematic from pymclevel import TAG_Compound from pymclevel import TAG_Short from pymclevel import TAG_Byte from pymclevel import TAG_Byte_Array from pymclevel import TAG_String from numpy import zeros, fromstring inputs = ( ("Biome", ("Ocean", "Plains", "Desert", "Extreme Hills", "Forest", "Taiga", "Swamppland", "River", "Hell (Nether)", "The End", "Frozen Ocean", "Frozen River", "Ice Plains", "Ice Mountains", "Mushroom Island", "Mushroom Island Shore", "Beach", "Desert Hills", "Forest Hills", "Taiga Hills", "Extreme Hills Edge", "Jungle", "Jungle Hills", "Jungle Edge", "Deep Ocean", "Stone Beach", "Cold Beach", "Birch Forest", "Birch Forest Hills", "Roofed Forest", "Cold Taiga", "Cold Taiga Hills", "Mega Taiga", "Mega Taiga Hills", "Extreme Hills+", "Savanna", "Savanna Plateau", "Mesa", "Mesa Plateau F", "Mesa Plateau", "The Void", "Sunflower Plains", "Desert M", "Extreme Hills M", "Flower Forest", "Taiga M", "Swampland M", "Ice Plains Spikes", "Ice Mountains Spikes", "Jungle M", "JungleEdge M", "Birch Forest M", "Birch Forest Hills M", "Roofed Forest M", "Cold Taiga M", "Mega Spruce Taiga", "Mega Spruce Taiga Hills", "Extreme Hills+ M", "Savanna M", "Savanna Plateau M", "Mesa (Bryce)", "Mesa Plateau F M", "Mesa Plateau M", "(Uncalculated)", )), ) biomes = { "Ocean": 0, "Plains": 1, "Desert": 2, "Extreme Hills": 3, "Forest": 4, "Taiga": 5, "Swamppland": 6, "River": 7, "Hell (Nether)": 8, "The End": 9, "Frozen Ocean": 10, "Frozen River": 11, "Ice Plains": 12, "Ice Mountains": 13, "Mushroom Island": 14, "Mushroom Island Shore": 15, "Beach": 16, "Desert Hills": 17, "Forest Hills": 18, "Taiga Hills": 19, "Extreme Hills Edge": 20, "Jungle": 21, "Jungle Hills": 22, "Jungle Edge": 23, "Deep Ocean": 24, "Stone Beach": 25, "Cold Beach": 26, "Birch Forest": 27, "Birch Forest Hills": 28, "Roofed Forest": 29, "Cold Taiga": 30, "Cold Taiga Hills": 31, "Mega Taiga": 32, "Mega Taiga Hills": 33, "Extreme Hills+": 34, "Savanna": 35, "Savanna Plateau": 36, "Mesa": 37, "Mesa Plateau F": 38, "Mesa Plateau": 39, "The Void": 127, "Sunflower Plains": 129, "Desert M": 130, "Extreme Hills M": 131, "Flower Forest": 132, "Taiga M": 133, "Swampland M": 134, "Ice Plains Spikes": 140, "Ice Mountains Spikes": 141, "Jungle M": 149, "JungleEdge M": 151, "Birch Forest M": 155, "Birch Forest Hills M": 156, "Roofed Forest M": 157, "Cold Taiga M": 158, "Mega Spruce Taiga": 160, "Mega Spruce Taiga Hills": 161, "Extreme Hills+ M": 162, "Savanna M": 163, "Savanna Plateau M": 164, "Mesa (Bryce)": 165, "Mesa Plateau F M": 166, "Mesa Plateau M": 167, "(Uncalculated)": -1, } def perform(level, box, options): biome = dict([(trn._(a), b) for a, b in biomes.items()])[options["Biome"]] minx = int(box.minx / 16) * 16 minz = int(box.minz / 16) * 16 for x in xrange(minx, box.maxx, 16): for z in xrange(minz, box.maxz, 16): # Pocket chunks root tag don't have any 'Level' member # But a 'Biome' member instead. chunk = level.getChunk(x / 16, z / 16) chunk.dirty = True chunk_root_tag = None if chunk.root_tag and 'Level' in chunk.root_tag.keys() and 'Biomes' in chunk.root_tag["Level"].keys(): chunk_root_tag = chunk.root_tag array = chunk_root_tag["Level"]["Biomes"].value else: shape = chunk.Biomes.shape array = fromstring(chunk.Biomes.tostring(), 'uint8') chunkx = int(x / 16) * 16 chunkz = int(z / 16) * 16 for bx in xrange(max(box.minx, chunkx), min(box.maxx, chunkx + 16)): for bz in xrange(max(box.minz, chunkz), min(box.maxz, chunkz + 16)): idx = 16 * (bz - chunkz) + (bx - chunkx) array[idx] = biome if chunk_root_tag: chunk_root_tag["Level"]["Biomes"].value = array else: array.shape = shape chunk.Biomes = array
5,569
29.271739
114
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/smooth.py
from numpy import zeros, array import itertools from pymclevel.level import extractHeights terrainBlocktypes = [1, 2, 3, 7, 12, 13, 14, 15, 16, 56, 73, 74, 87, 88, 89] terrainBlockmask = zeros((256,), dtype='bool') terrainBlockmask[terrainBlocktypes] = True # inputs = ( ("Repeat count", (1, 50)), ) displayName = "Smooth - 2D" def perform(level, box, options): if box.volume > 16000000: raise ValueError("Volume too big for this filter method!") repeatCount = options["Repeat count"] schema = level.extractSchematic(box) schema.removeEntitiesInBox(schema.bounds) schema.removeTileEntitiesInBox(schema.bounds) for i in xrange(repeatCount): terrainBlocks = terrainBlockmask[schema.Blocks] heightmap = extractHeights(terrainBlocks) # terrainBlocks |= schema.Blocks == 0 nonTerrainBlocks = ~terrainBlocks nonTerrainBlocks &= schema.Blocks != 0 newHeightmap = (heightmap[1:-1, 1:-1] + ( heightmap[0:-2, 1:-1] + heightmap[2:, 1:-1] + heightmap[1:-1, 0:-2] + heightmap[1:-1, 2:]) * 0.7) / 3.8 #heightmap -= 0.5; newHeightmap += 0.5 newHeightmap[newHeightmap < 0] = 0 newHeightmap[newHeightmap > schema.Height] = schema.Height newHeightmap = array(newHeightmap, dtype='uint16') for x, z in itertools.product(xrange(1, schema.Width - 1), xrange(1, schema.Length - 1)): oh = heightmap[x, z] nh = newHeightmap[x - 1, z - 1] d = nh - oh column = array(schema.Blocks[x, z]) column[nonTerrainBlocks[x, z]] = 0 #schema.Blocks[x,z][nonTerrainBlocks[x,z]] = 0 if nh > oh: column[d:] = schema.Blocks[x, z, :-d] if d > oh: column[:d] = schema.Blocks[x, z, 0] if nh < oh: column[:d] = schema.Blocks[x, z, -d:] column[d:oh + 1] = schema.Blocks[x, z, min(oh + 1, schema.Height - 1)] #preserve non-terrain blocks column[~terrainBlockmask[column]] = 0 column[nonTerrainBlocks[x, z]] = schema.Blocks[x, z][nonTerrainBlocks[x, z]] schema.Blocks[x, z] = column level.copyBlocksFrom(schema, schema.bounds, box.origin)
2,281
32.072464
111
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/Forester.py
# Version 5 '''This takes a base MineCraft level and adds or edits trees. Place it in the folder where the save files are (usually .../.minecraft/saves) Requires mcInterface.py in the same folder.''' # Here are the variables you can edit. # This is the name of the map to edit. # Make a backup if you are experimenting! LOADNAME = "LevelSave" # How many trees do you want to add? TREECOUNT = 12 # Where do you want the new trees? # X, and Z are the map coordinates X = 66 Z = -315 # How large an area do you want the trees to be in? # for example, RADIUS = 10 will make place trees randomly in # a circular area 20 blocks wide. RADIUS = 80 # NOTE: tree density will be higher in the center than at the edges. # Which shapes would you like the trees to be? # these first three are best suited for small heights, from 5 - 10 # "normal" is the normal minecraft shape, it only gets taller and shorter # "bamboo" a trunk with foliage, it only gets taller and shorter # "palm" a trunk with a fan at the top, only gets taller and shorter # "stickly" selects randomly from "normal", "bamboo" and "palm" # these last five are best suited for very large trees, heights greater than 8 # "round" procedural spherical shaped tree, can scale up to immense size # "cone" procedural, like a pine tree, also can scale up to immense size # "procedural" selects randomly from "round" and "conical" # "rainforest" many slender trees, most at the lower range of the height, # with a few at the upper end. # "mangrove" makes mangrove trees (see PLANTON below). SHAPE = "procedural" # What height should the trees be? # Specifies the average height of the tree # Examples: # 5 is normal minecraft tree # 3 is minecraft tree with foliage flush with the ground # 10 is very tall trees, they will be hard to chop down # NOTE: for round and conical, this affects the foliage size as well. # CENTERHEIGHT is the height of the trees at the center of the area # ie, when radius = 0 CENTERHEIGHT = 55 # EDGEHEIGHT is the height at the trees at the edge of the area. # ie, when radius = RADIUS EDGEHEIGHT = 25 # What should the variation in HEIGHT be? # actual value +- variation # default is 1 # Example: # HEIGHT = 8 and HEIGHTVARIATION = 3 will result in # trunk heights from 5 to 11 # value is clipped to a max of HEIGHT # for a good rainforest, set this value not more than 1/2 of HEIGHT HEIGHTVARIATION = 12 # Do you want branches, trunk, and roots? # True makes all of that # False does not create the trunk and branches, or the roots (even if they are # enabled further down) WOOD = True # Trunk thickness multiplyer # from zero (super thin trunk) to whatever huge number you can think of. # Only works if SHAPE is not a "stickly" subtype # Example: # 1.0 is the default, it makes decently normal sized trunks # 0.3 makes very thin trunks # 4.0 makes a thick trunk (good for HOLLOWTRUNK). # 10.5 will make a huge thick trunk. Not even kidding. Makes spacious # hollow trunks though! TRUNKTHICKNESS = 1.0 # Trunk height, as a fraction of the tree # Only works on "round" shaped trees # Sets the height of the crown, where the trunk ends and splits # Examples: # 0.7 the default value, a bit more than half of the height # 0.3 good for a fan-like tree # 1.0 the trunk will extend to the top of the tree, and there will be no crown # 2.0 the trunk will extend out the top of the foliage, making the tree appear # like a cluster of green grapes impaled on a spike. TRUNKHEIGHT = 0.7 # Do you want the trunk and tree broken off at the top? # removes about half of the top of the trunk, and any foliage # and branches that would attach above it. # Only works if SHAPE is not a "stickly" subtype # This results in trees that are shorter than the height settings # True does that stuff # False makes a normal tree (default) BROKENTRUNK = False # Note, this works well with HOLLOWTRUNK (below) turned on as well. # Do you want the trunk to be hollow (or filled) inside? # Only works with larger sized trunks. # Only works if SHAPE is not a "stickly" subtype # True makes the trunk hollow (or filled with other stuff) # False makes a solid trunk (default) HOLLOWTRUNK = False # Note, this works well with BROKENTRUNK set to true (above) # Further note, you may want to use a large value for TRUNKTHICKNESS # How many branches should there be? # General multiplyer for the number of branches # However, it will not make more branches than foliage clusters # so to garuntee a branch to every foliage cluster, set it very high, like 10000 # this also affects the number of roots, if they are enabled. # Examples: # 1.0 is normal # 0.5 will make half as many branches # 2.0 will make twice as mnay branches # 10000 will make a branch to every foliage cluster (I'm pretty sure) BRANCHDENSITY = 1.0 # do you want roots from the bottom of the tree? # Only works if SHAPE is "round" or "cone" or "procedural" # "yes" roots will penetrate anything, and may enter underground caves. # "tostone" roots will be stopped by stone (default see STOPSROOTS below). # There may be some penetration. # "hanging" will hang downward in air. Good for "floating" type maps # (I really miss "floating" terrain as a default option) # "no" roots will not be generated ROOTS = "tostone" # Do you want root buttresses? # These make the trunk not-round at the base, seen in tropical or old trees. # This option generally makes the trunk larger. # Only works if SHAPE is "round" or "cone" or "procedural" # Options: # True makes root butresses # False leaves them out ROOTBUTTRESSES = True # Do you want leaves on the trees? # True there will be leaves # False there will be no leaves FOLIAGE = True # How thick should the foliage be # General multiplyer for the number of foliage clusters # Examples: # 1.0 is normal # 0.3 will make very sparse spotty trees, half as many foliage clusters # 2.0 will make dense foliage, better for the "rainforests" SHAPE FOLIAGEDENSITY = 1.0 # Limit the tree height to the top of the map? # True the trees will not grow any higher than the top of the map # False the trees may be cut off by the top of the map MAPHEIGHTLIMIT = True # add lights in the middle of foliage clusters # for those huge trees that get so dark underneath # or for enchanted forests that should glow and stuff # Only works if SHAPE is "round" or "cone" or "procedural" # 0 makes just normal trees # 1 adds one light inside the foliage clusters for a bit of light # 2 adds two lights around the base of each cluster, for more light # 4 adds lights all around the base of each cluster for lots of light LIGHTTREE = 0 # Do you want to only place trees near existing trees? # True will only plant new trees near existing trees. # False will not check for existing trees before planting. # NOTE: the taller the tree, the larger the forest needs to be to qualify # OTHER NOTE: this feature has not been extensively tested. # IF YOU HAVE PROBLEMS: SET TO False ONLYINFORESTS = False ##################### # Advanced options! # ##################### # What kind of material should the "wood" be made of? # defaults to 17 WOODMAT = 17 # What data value should the wood blocks have? # Some blocks, like wood, leaves, and cloth change # apperance with different data values # defaults to 0 WOODDATA = 0 # What kind of material should the "leaves" be made of? # defaults to 18 LEAFMAT = 18 # What data value should the leaf blocks have? # Some blocks, like wood, leaves, and cloth change # apperance with different data values # defaults to 0 LEAFDATA = 0 # What kind of material should the "lights" be made of? # defaults to 89 (glowstone) LIGHTMAT = 89 # What data value should the light blocks have? # defaults to 0 LIGHTDATA = 0 # What kind of material would you like the "hollow" trunk filled with? # defaults to 0 (air) TRUNKFILLMAT = 0 # What data value would you like the "hollow" trunk filled with? # defaults to 0 TRUNKFILLDATA = 0 # What kind of blocks should the trees be planted on? # Use the Minecraft index. # Examples # 2 is grass (the default) # 3 is dirt # 1 is stone (an odd choice) # 12 is sand (for beach or desert) # 9 is water (if you want an aquatic forest) # this is a list, and comma seperated. # example: [2, 3] # will plant trees on grass or dirt PLANTON = [2] # What kind of blocks should stop the roots? # a list of block id numbers like PLANTON # Only works if ROOTS = "tostone" # default, [1] (stone) # if you want it to be stopped by other block types, add it to the list STOPSROOTS = [1] # What kind of blocks should stop branches? # same as STOPSROOTS above, but is always turned on # defaults to stone, cobblestone, and glass # set it to [] if you want branches to go through everything STOPSBRANCHES = [1, 4, 20] # How do you want to interpolate from center to edge? # "linear" makes a cone-shaped forest # This is the only option at present INTERPOLATION = "linear" # Do a rough recalculation of the lighting? # Slows it down to do a very rough and incomplete re-light. # If you want to really fix the lighting, use a seperate re-lighting tool. # True do the rough fix # False don't bother LIGHTINGFIX = True # How many times do you want to try to find a location? # it will stop planing after MAXTRIES has been exceeded. # Set to smaller numbers to abort quicker, or larger numbers # if you want to keep trying for a while. # NOTE: the number of trees will not exceed this number # Default: 1000 MAXTRIES = 1000 # Do you want lots of text telling you waht is going on? # True lots of text (default). Good for debugging. # False no text VERBOSE = True ############################################################## # Don't edit below here unless you know what you are doing # ############################################################## # input filtering TREECOUNT = int(TREECOUNT) if TREECOUNT < 0: TREECOUNT = 0 if SHAPE not in ["normal", "bamboo", "palm", "stickly", "round", "cone", "procedural", "rainforest", "mangrove"]: if VERBOSE: print("SHAPE not set correctly, using 'procedural'.") SHAPE = "procedural" if CENTERHEIGHT < 1: CENTERHEIGHT = 1 if EDGEHEIGHT < 1: EDGEHEIGHT = 1 minheight = min(CENTERHEIGHT, EDGEHEIGHT) if HEIGHTVARIATION > minheight: HEIGHTVARIATION = minheight if INTERPOLATION not in ["linear"]: if VERBOSE: print("INTERPOLATION not set correctly, using 'linear'.") INTERPOLATION = "linear" if WOOD not in [True, False]: if VERBOSE: print("WOOD not set correctly, using True") WOOD = True if TRUNKTHICKNESS < 0.0: TRUNKTHICKNESS = 0.0 if TRUNKHEIGHT < 0.0: TRUNKHEIGHT = 0.0 if ROOTS not in ["yes", "tostone", "hanging", "no"]: if VERBOSE: print("ROOTS not set correctly, using 'no' and creating no roots") ROOTS = "no" if ROOTBUTTRESSES not in [True, False]: if VERBOSE: print("ROOTBUTTRESSES not set correctly, using False") ROOTBUTTRESSES = False if FOLIAGE not in [True, False]: if VERBOSE: print("FOLIAGE not set correctly, using True") ROOTBUTTRESSES = True if FOLIAGEDENSITY < 0.0: FOLIAGEDENSITY = 0.0 if BRANCHDENSITY < 0.0: BRANCHDENSITY = 0.0 if MAPHEIGHTLIMIT not in [True, False]: if VERBOSE: print("MAPHEIGHTLIMIT not set correctly, using False") MAPHEIGHTLIMIT = False if LIGHTTREE not in [0, 1, 2, 4]: if VERBOSE: print("LIGHTTREE not set correctly, using 0 for no torches") LIGHTTREE = 0 # assemble the material dictionaries WOODINFO = {'B': WOODMAT, 'D': WOODDATA} LEAFINFO = {'B': LEAFMAT, 'D': LEAFDATA} LIGHTINFO = {'B': LIGHTMAT, 'D': LIGHTDATA} TRUNKFILLINFO = {'B': TRUNKFILLMAT, 'D': TRUNKFILLDATA} # The following is an interface class for .mclevel data for minecraft savefiles. # The following also includes a useful coordinate to index convertor and several # other useful functions. import mcInterface #some handy functions def dist_to_mat(cord, vec, matidxlist, mcmap, invert=False, limit=False): '''travel from cord along vec and return how far it was to a point of matidx the distance is returned in number of iterations. If the edge of the map is reached, then return the number of iterations as well. if invert == True, search for anything other than those in matidxlist ''' assert isinstance(mcmap, mcInterface.SaveFile) block = mcmap.block curcord = [i + .5 for i in cord] iterations = 0 on_map = True while on_map: x = int(curcord[0]) y = int(curcord[1]) z = int(curcord[2]) return_dict = block(x, y, z) if return_dict is None: break else: block_value = return_dict['B'] if (block_value in matidxlist) and (invert is False): break elif (block_value not in matidxlist) and invert: break else: curcord = [curcord[i] + vec[i] for i in range(3)] iterations += 1 if limit and iterations > limit: break return iterations # This is the end of the MCLevel interface. # Now, on to the actual code. from random import random, choice, sample from math import sqrt, sin, cos, pi def calc_column_lighting(x, z, mclevel): '''Recalculate the sky lighting of the column.''' # Begin at the top with sky light level 15. cur_light = 15 # traverse the column until cur_light == 0 # and the existing light values are also zero. y = 255 get_block = mclevel.block set_block = mclevel.set_block get_height = mclevel.retrieve_heightmap set_height = mclevel.set_heightmap #get the current heightmap cur_height = get_height(x, z) # set a flag that the highest point has been updated height_updated = False # if this doesn't exist, the block doesn't exist either, abort. if cur_height is None: return None light_reduction_lookup = {0: 0, 20: 0, 18: 1, 8: 2, 79: 2} while True: #get the block sky light and type block_info = get_block(x, y, z, 'BS') block_light = block_info['S'] block_type = block_info['B'] # update the height map if it hasn't been updated yet, # and the current block reduces light if (not height_updated) and (block_type not in (0, 20)): new_height = y + 1 if new_height == 256: new_height = 255 set_height(x, new_height, z) height_updated = True #compare block with cur_light, escape if both 0 if block_light == 0 and cur_light == 0: break #set the block light if necessary if block_light != cur_light: set_block(x, y, z, {'S': cur_light}) #set the new cur_light if block_type in light_reduction_lookup: # partial light reduction light_reduction = light_reduction_lookup[block_type] else: # full light reduction light_reduction = 16 cur_light += -light_reduction if cur_light < 0: cur_light = 0 #increment and check y y += -1 if y < 0: break class ReLight(object): '''keep track of which squares need to be relit, and then relight them''' def add(self, x, z): coords = (x, z) self.all_columns.add(coords) def calc_lighting(self): mclevel = self.save_file for column_coords in self.all_columns: # recalculate the lighting x = column_coords[0] z = column_coords[1] calc_column_lighting(x, z, mclevel) def __init__(self): self.all_columns = set() self.save_file = None relight_master = ReLight() def assign_value(x, y, z, values, save_file): '''Assign an index value to a location in mcmap. If the index is outside the bounds of the map, return None. If the assignment succeeds, return True. ''' if y > 255: return None result = save_file.set_block(x, y, z, values) if LIGHTINGFIX: relight_master.add(x, z) return result class Tree(object): '''Set up the interface for tree objects. Designed for subclassing. ''' def prepare(self, mcmap): '''initialize the internal values for the Tree object. ''' return None def maketrunk(self, mcmap): '''Generate the trunk and enter it in mcmap. ''' return None def makefoliage(self, mcmap): """Generate the foliage and enter it in mcmap. Note, foliage will disintegrate if there is no log nearby""" return None def copy(self, other): '''Copy the essential values of the other tree object into self. ''' self.pos = other.pos self.height = other.height def __init__(self, pos=[0, 0, 0], height=1): '''Accept values for the position and height of a tree. Store them in self. ''' self.pos = pos self.height = height class StickTree(Tree): '''Set up the trunk for trees with a trunk width of 1 and simple geometry. Designed for sublcassing. Only makes the trunk. ''' def maketrunk(self, mcmap): x = self.pos[0] y = self.pos[1] z = self.pos[2] for i in range(self.height): assign_value(x, y, z, WOODINFO, mcmap) y += 1 class NormalTree(StickTree): '''Set up the foliage for a 'normal' tree. This tree will be a single bulb of foliage above a single width trunk. This shape is very similar to the default Minecraft tree. ''' def makefoliage(self, mcmap): """note, foliage will disintegrate if there is no foliage below, or if there is no "log" block within range 2 (square) at the same level or one level below""" topy = self.pos[1] + self.height - 1 start = topy - 2 end = topy + 2 for y in range(start, end): if y > start + 1: rad = 1 else: rad = 2 for xoff in range(-rad, rad + 1): for zoff in range(-rad, rad + 1): if (random() > 0.618 and abs(xoff) == abs(zoff) and abs(xoff) == rad ): continue x = self.pos[0] + xoff z = self.pos[2] + zoff assign_value(x, y, z, LEAFINFO, mcmap) class BambooTree(StickTree): '''Set up the foliage for a bamboo tree. Make foliage sparse and adjacent to the trunk. ''' def makefoliage(self, mcmap): start = self.pos[1] end = self.pos[1] + self.height + 1 for y in range(start, end): for _ in [0, 1]: xoff = choice([-1, 1]) zoff = choice([-1, 1]) x = self.pos[0] + xoff z = self.pos[2] + zoff assign_value(x, y, z, LEAFINFO, mcmap) class PalmTree(StickTree): '''Set up the foliage for a palm tree. Make foliage stick out in four directions from the top of the trunk. ''' def makefoliage(self, mcmap): y = self.pos[1] + self.height for xoff in range(-2, 3): for zoff in range(-2, 3): if abs(xoff) == abs(zoff): x = self.pos[0] + xoff z = self.pos[2] + zoff assign_value(x, y, z, LEAFINFO, mcmap) class ProceduralTree(Tree): '''Set up the methods for a larger more complicated tree. This tree type has roots, a trunk, and branches all of varying width, and many foliage clusters. MUST BE SUBCLASSED. Specifically, self.foliage_shape must be set. Subclass 'prepare' and 'shapefunc' to make different shaped trees. ''' @staticmethod def crossection(center, radius, diraxis, matidx, mcmap): '''Create a round section of type matidx in mcmap. Passed values: center = [x, y, z] for the coordinates of the center block radius = <number> as the radius of the section. May be a float or int. diraxis: The list index for the axis to make the section perpendicular to. 0 indicates the x axis, 1 the y, 2 the z. The section will extend along the other two axies. matidx = <int> the integer value to make the section out of. mcmap = the array generated by make_mcmap matdata = <int> the integer value to make the block data value. ''' rad = int(radius + .618) if rad <= 0: return None secidx1 = (diraxis - 1) % 3 secidx2 = (1 + diraxis) % 3 coord = [0, 0, 0] for off1 in range(-rad, rad + 1): for off2 in range(-rad, rad + 1): thisdist = sqrt((abs(off1) + .5) ** 2 + (abs(off2) + .5) ** 2) if thisdist > radius: continue pri = center[diraxis] sec1 = center[secidx1] + off1 sec2 = center[secidx2] + off2 coord[diraxis] = pri coord[secidx1] = sec1 coord[secidx2] = sec2 assign_value(coord[0], coord[1], coord[2], matidx, mcmap) def shapefunc(self, y): '''Take y and return a radius for the location of the foliage cluster. If no foliage cluster is to be created, return None Designed for sublcassing. Only makes clusters close to the trunk. ''' if random() < 100. / (self.height ** 2) and y < self.trunkheight: return self.height * .12 return None def foliagecluster(self, center, mcmap): '''generate a round cluster of foliage at the location center. The shape of the cluster is defined by the list self.foliage_shape. This list must be set in a subclass of ProceduralTree. ''' level_radius = self.foliage_shape x = center[0] y = center[1] z = center[2] for i in level_radius: self.crossection([x, y, z], i, 1, LEAFINFO, mcmap) y += 1 def taperedcylinder(self, start, end, startsize, endsize, mcmap, blockdata): '''Create a tapered cylinder in mcmap. start and end are the beginning and ending coordinates of form [x, y, z]. startsize and endsize are the beginning and ending radius. The material of the cylinder is WOODMAT. ''' # delta is the coordinate vector for the difference between # start and end. delta = [int(end[i] - start[i]) for i in range(3)] # primidx is the index (0, 1, or 2 for x, y, z) for the coordinate # which has the largest overall delta. maxdist = max(delta, key=abs) if maxdist == 0: return None primidx = delta.index(maxdist) # secidx1 and secidx2 are the remaining indicies out of [0, 1, 2]. secidx1 = (primidx - 1) % 3 secidx2 = (1 + primidx) % 3 # primsign is the digit 1 or -1 depending on whether the limb is headed # along the positive or negative primidx axis. primsign = int(delta[primidx] / abs(delta[primidx])) # secdelta1 and ...2 are the amount the associated values change # for every step along the prime axis. secdelta1 = delta[secidx1] secfac1 = float(secdelta1) / delta[primidx] secdelta2 = delta[secidx2] secfac2 = float(secdelta2) / delta[primidx] # Initialize coord. These values could be anything, since # they are overwritten. coord = [0, 0, 0] # Loop through each crossection along the primary axis, # from start to end. endoffset = delta[primidx] + primsign for primoffset in range(0, endoffset, primsign): primloc = start[primidx] + primoffset secloc1 = int(start[secidx1] + primoffset * secfac1) secloc2 = int(start[secidx2] + primoffset * secfac2) coord[primidx] = primloc coord[secidx1] = secloc1 coord[secidx2] = secloc2 primdist = abs(delta[primidx]) radius = endsize + (startsize - endsize) * abs(delta[primidx] - primoffset) / primdist self.crossection(coord, radius, primidx, blockdata, mcmap) def makefoliage(self, mcmap): '''Generate the foliage for the tree in mcmap. ''' """note, foliage will disintegrate if there is no foliage below, or if there is no "log" block within range 2 (square) at the same level or one level below""" foliage_coords = self.foliage_cords for coord in foliage_coords: self.foliagecluster(coord, mcmap) for cord in foliage_coords: assign_value(cord[0], cord[1], cord[2], WOODINFO, mcmap) if LIGHTTREE == 1: assign_value(cord[0], cord[1] + 1, cord[2], LIGHTINFO, mcmap) elif LIGHTTREE in [2, 4]: assign_value(cord[0] + 1, cord[1], cord[2], LIGHTINFO, mcmap) assign_value(cord[0] - 1, cord[1], cord[2], LIGHTINFO, mcmap) if LIGHTTREE == 4: assign_value(cord[0], cord[1], cord[2] + 1, LIGHTINFO, mcmap) assign_value(cord[0], cord[1], cord[2] - 1, LIGHTINFO, mcmap) def makebranches(self, mcmap): '''Generate the branches and enter them in mcmap. ''' treeposition = self.pos height = self.height topy = treeposition[1] + int(self.trunkheight + 0.5) # endrad is the base radius of the branches at the trunk endrad = self.trunkradius * (1 - self.trunkheight / height) if endrad < 1.0: endrad = 1.0 for coord in self.foliage_cords: dist = (sqrt(float(coord[0] - treeposition[0]) ** 2 + float(coord[2] - treeposition[2]) ** 2)) ydist = coord[1] - treeposition[1] # value is a magic number that weights the probability # of generating branches properly so that # you get enough on small trees, but not too many # on larger trees. # Very difficult to get right... do not touch! value = (self.branchdensity * 220 * height) / ((ydist + dist) ** 3) if value < random(): continue posy = coord[1] slope = self.branchslope + (0.5 - random()) * .16 if coord[1] - dist * slope > topy: # Another random rejection, for branches between # the top of the trunk and the crown of the tree threshhold = 1 / float(height) if random() < threshhold: continue branchy = topy basesize = endrad else: branchy = posy - dist * slope basesize = (endrad + (self.trunkradius - endrad) * (topy - branchy) / self.trunkheight) startsize = (basesize * (1 + random()) * .618 * (dist / height) ** 0.618) rndr = sqrt(random()) * basesize * 0.618 rndang = random() * 2 * pi rndx = int(rndr * sin(rndang) + 0.5) rndz = int(rndr * cos(rndang) + 0.5) startcoord = [treeposition[0] + rndx, int(branchy), treeposition[2] + rndz] if startsize < 1.0: startsize = 1.0 endsize = 1.0 self.taperedcylinder(startcoord, coord, startsize, endsize, mcmap, WOODINFO) def makeroots(self, rootbases, mcmap): '''generate the roots and enter them in mcmap. rootbases = [[x, z, base_radius], ...] and is the list of locations the roots can originate from, and the size of that location. ''' treeposition = self.pos height = self.height for coord in self.foliage_cords: # First, set the threshhold for randomly selecting this # coordinate for root creation. dist = (sqrt(float(coord[0] - treeposition[0]) ** 2 + float(coord[2] - treeposition[2]) ** 2)) ydist = coord[1] - treeposition[1] value = (self.branchdensity * 220 * height) / ((ydist + dist) ** 3) # Randomly skip roots, based on the above threshold if value < random(): continue # initialize the internal variables from a selection of # starting locations. rootbase = choice(rootbases) rootx = rootbase[0] rootz = rootbase[1] rootbaseradius = rootbase[2] # Offset the root origin location by a random amount # (radialy) from the starting location. rndr = (sqrt(random()) * rootbaseradius * .618) rndang = random() * 2 * pi rndx = int(rndr * sin(rndang) + 0.5) rndz = int(rndr * cos(rndang) + 0.5) rndy = int(random() * rootbaseradius * 0.5) startcoord = [rootx + rndx, treeposition[1] + rndy, rootz + rndz] # offset is the distance from the root base to the root tip. offset = [startcoord[i] - coord[i] for i in range(3)] # If this is a mangrove tree, make the roots longer. if SHAPE == "mangrove": offset = [int(val * 1.618 - 1.5) for val in offset] endcoord = [startcoord[i] + offset[i] for i in range(3)] rootstartsize = (rootbaseradius * 0.618 * abs(offset[1]) / (height * 0.618)) if rootstartsize < 1.0: rootstartsize = 1.0 endsize = 1.0 # If ROOTS is set to "tostone" or "hanging" we need to check # along the distance for collision with existing materials. if ROOTS in ["tostone", "hanging"]: offlength = sqrt(float(offset[0]) ** 2 + float(offset[1]) ** 2 + float(offset[2]) ** 2) if offlength < 1: continue rootmid = endsize # vec is a unit vector along the direction of the root. vec = [offset[i] / offlength for i in range(3)] if ROOTS == "tostone": searchindex = STOPSROOTS elif ROOTS == "hanging": searchindex = [0] # startdist is how many steps to travel before starting to # search for the material. It is used to ensure that large # roots will go some distance before changing directions # or stopping. startdist = int(random() * 6 * sqrt(rootstartsize) + 2.8) # searchstart is the coordinate where the search should begin searchstart = [startcoord[i] + startdist * vec[i] for i in range(3)] # dist stores how far the search went (including searchstart) # before encountering the expected marterial. dist = startdist + dist_to_mat(searchstart, vec, searchindex, mcmap, limit=offlength) # If the distance to the material is less than the length # of the root, change the end point of the root to where # the search found the material. if dist < offlength: # rootmid is the size of the crossection at endcoord. rootmid += (rootstartsize - endsize) * (1 - dist / offlength) # endcoord is the midpoint for hanging roots, # and the endpoint for roots stopped by stone. endcoord = [startcoord[i] + int(vec[i] * dist) for i in range(3)] if ROOTS == "hanging": # remaining_dist is how far the root had left # to go when it was stopped. remaining_dist = offlength - dist # Initialize bottomcord to the stopping point of # the root, and then hang straight down # a distance of remaining_dist. bottomcord = endcoord[:] bottomcord[1] += -int(remaining_dist) # Make the hanging part of the hanging root. self.taperedcylinder(endcoord, bottomcord, rootmid, endsize, mcmap, WOODINFO) # make the beginning part of hanging or "tostone" roots self.taperedcylinder(startcoord, endcoord, rootstartsize, rootmid, mcmap, WOODINFO) # If you aren't searching for stone or air, just make the root. else: self.taperedcylinder(startcoord, endcoord, rootstartsize, endsize, mcmap, WOODINFO) def maketrunk(self, mcmap): '''Generate the trunk, roots, and branches in mcmap. ''' height = self.height trunkheight = self.trunkheight trunkradius = self.trunkradius treeposition = self.pos starty = treeposition[1] midy = treeposition[1] + int(trunkheight * .382) topy = treeposition[1] + int(trunkheight + 0.5) # In this method, x and z are the position of the trunk. x = treeposition[0] z = treeposition[2] end_size_factor = trunkheight / height midrad = trunkradius * (1 - end_size_factor * .5) endrad = trunkradius * (1 - end_size_factor) if endrad < 1.0: endrad = 1.0 if midrad < endrad: midrad = endrad # Make the root buttresses, if indicated if ROOTBUTTRESSES or SHAPE == "mangrove": # The start radius of the trunk should be a little smaller if we # are using root buttresses. startrad = trunkradius * .8 # rootbases is used later in self.makeroots(...) as # starting locations for the roots. rootbases = [[x, z, startrad]] buttress_radius = trunkradius * 0.382 # posradius is how far the root buttresses should be offset # from the trunk. posradius = trunkradius # In mangroves, the root buttresses are much more extended. if SHAPE == "mangrove": posradius *= 2.618 num_of_buttresses = int(sqrt(trunkradius) + 3.5) for i in range(num_of_buttresses): rndang = random() * 2 * pi thisposradius = posradius * (0.9 + random() * .2) # thisx and thisz are the x and z position for the base of # the root buttress. thisx = x + int(thisposradius * sin(rndang)) thisz = z + int(thisposradius * cos(rndang)) # thisbuttressradius is the radius of the buttress. # Currently, root buttresses do not taper. thisbuttressradius = buttress_radius * (0.618 + random()) if thisbuttressradius < 1.0: thisbuttressradius = 1.0 # Make the root buttress. self.taperedcylinder([thisx, starty, thisz], [x, midy, z], thisbuttressradius, thisbuttressradius, mcmap, WOODINFO) # Add this root buttress as a possible location at # which roots can spawn. rootbases += [[thisx, thisz, thisbuttressradius]] else: # If root buttresses are turned off, set the trunk radius # to normal size. startrad = trunkradius rootbases = [[x, z, startrad]] # Make the lower and upper sections of the trunk. self.taperedcylinder([x, starty, z], [x, midy, z], startrad, midrad, mcmap, WOODINFO) self.taperedcylinder([x, midy, z], [x, topy, z], midrad, endrad, mcmap, WOODINFO) #Make the branches self.makebranches(mcmap) #Make the roots, if indicated. if ROOTS in ["yes", "tostone", "hanging"]: self.makeroots(rootbases, mcmap) # Hollow the trunk, if specified # check to make sure that the trunk is large enough to be hollow if trunkradius > 2 and HOLLOWTRUNK: # wall thickness is actually the double the wall thickness # it is a diameter difference, not a radius difference. wall_thickness = (1 + trunkradius * 0.1 * random()) if wall_thickness < 1.3: wall_thickness = 1.3 base_radius = trunkradius - wall_thickness if base_radius < 1: base_radius = 1.0 mid_radius = midrad - wall_thickness top_radius = endrad - wall_thickness # the starting x and y can be offset by up to the wall thickness. base_offset = int(wall_thickness) x_choices = [i for i in range(x - base_offset, x + base_offset + 1)] start_x = choice(x_choices) z_choices = [i for i in range(z - base_offset, z + base_offset + 1)] start_z = choice(z_choices) self.taperedcylinder([start_x, starty, start_z], [x, midy, z], base_radius, mid_radius, mcmap, TRUNKFILLINFO) hollow_top_y = int(topy + trunkradius + 1.5) self.taperedcylinder([x, midy, z], [x, hollow_top_y, z], mid_radius, top_radius, mcmap, TRUNKFILLINFO) def prepare(self, mcmap): '''Initialize the internal values for the Tree object. Primarily, sets up the foliage cluster locations. ''' treeposition = self.pos self.trunkradius = .618 * sqrt(self.height * TRUNKTHICKNESS) if self.trunkradius < 1: self.trunkradius = 1 if BROKENTRUNK: self.trunkheight = self.height * (.3 + random() * .4) yend = int(treeposition[1] + self.trunkheight + .5) else: self.trunkheight = self.height yend = int(treeposition[1] + self.height) self.branchdensity = BRANCHDENSITY / FOLIAGEDENSITY topy = treeposition[1] + int(self.trunkheight + 0.5) foliage_coords = [] ystart = treeposition[1] num_of_clusters_per_y = int(1.5 + (FOLIAGEDENSITY * self.height / 19.) ** 2) if num_of_clusters_per_y < 1: num_of_clusters_per_y = 1 # make sure we don't spend too much time off the top of the map if yend > 255: yend = 255 if ystart > 255: ystart = 255 for y in range(yend, ystart, -1): for i in range(num_of_clusters_per_y): shapefac = self.shapefunc(y - ystart) if shapefac is None: continue r = (sqrt(random()) + .328) * shapefac theta = random() * 2 * pi x = int(r * sin(theta)) + treeposition[0] z = int(r * cos(theta)) + treeposition[2] # if there are values to search in STOPSBRANCHES # then check to see if this cluster is blocked # by stuff, like dirt or rock, or whatever if len(STOPSBRANCHES): dist = (sqrt(float(x - treeposition[0]) ** 2 + float(z - treeposition[2]) ** 2)) slope = self.branchslope if y - dist * slope > topy: # the top of the tree starty = topy else: starty = y - dist * slope # the start position of the search start = [treeposition[0], starty, treeposition[2]] offset = [x - treeposition[0], y - starty, z - treeposition[2]] offlength = sqrt(offset[0] ** 2 + offset[1] ** 2 + offset[2] ** 2) # if the branch is as short as... nothing, don't bother. if offlength < 1: continue # unit vector for the search vec = [offset[i] / offlength for i in range(3)] mat_dist = dist_to_mat(start, vec, STOPSBRANCHES, mcmap, limit=offlength + 3) # after all that, if you find something, don't add # this coordinate to the list if mat_dist < offlength + 2: continue foliage_coords += [[x, y, z]] self.foliage_cords = foliage_coords class RoundTree(ProceduralTree): '''This kind of tree is designed to resemble a deciduous tree. ''' def prepare(self, mcmap): self.branchslope = 0.382 ProceduralTree.prepare(self, mcmap) self.foliage_shape = [2, 3, 3, 2.5, 1.6] self.trunkradius *= 0.8 self.trunkheight *= TRUNKHEIGHT def shapefunc(self, y): twigs = ProceduralTree.shapefunc(self, y) if twigs is not None: return twigs if y < self.height * (.282 + .1 * sqrt(random())): return None radius = self.height / 2. adj = self.height / 2. - y if adj == 0: dist = radius elif abs(adj) >= radius: dist = 0 else: dist = sqrt((radius ** 2) - (adj ** 2)) dist *= .618 return dist class ConeTree(ProceduralTree): '''this kind of tree is designed to resemble a conifer tree. ''' # woodType is the kind of wood the tree has, a data value woodType = 1 def prepare(self, mcmap): self.branchslope = 0.15 ProceduralTree.prepare(self, mcmap) self.foliage_shape = [3, 2.6, 2, 1] self.trunkradius *= 0.5 def shapefunc(self, y): twigs = ProceduralTree.shapefunc(self, y) if twigs is not None: return twigs if y < self.height * (.25 + .05 * sqrt(random())): return None radius = (self.height - y) * 0.382 if radius < 0: radius = 0 return radius class RainforestTree(ProceduralTree): '''This kind of tree is designed to resemble a rainforest tree. ''' def prepare(self, mcmap): self.foliage_shape = [3.4, 2.6] self.branchslope = 1.0 ProceduralTree.prepare(self, mcmap) self.trunkradius *= 0.382 self.trunkheight *= .9 def shapefunc(self, y): if y < self.height * 0.8: if EDGEHEIGHT < self.height: twigs = ProceduralTree.shapefunc(self, y) if (twigs is not None) and random() < 0.07: return twigs return None else: width = self.height * .382 topdist = (self.height - y) / (self.height * 0.2) dist = width * (0.618 + topdist) * (0.618 + random()) * 0.382 return dist class MangroveTree(RoundTree): '''This kind of tree is designed to resemble a mangrove tree. ''' def prepare(self, mcmap): self.branchslope = 1.0 RoundTree.prepare(self, mcmap) self.trunkradius *= 0.618 def shapefunc(self, y): val = RoundTree.shapefunc(self, y) if val is None: return val val *= 1.618 return val def planttrees(mcmap, treelist): '''Take mcmap and add trees to random locations on the surface to treelist. ''' assert isinstance(mcmap, mcInterface.SaveFile) # keep looping until all the trees are placed # calc the radius difference, for interpolation in_out_dif = EDGEHEIGHT - CENTERHEIGHT if VERBOSE: print('Tree Locations: x, y, z, tree height') tries = 0 max_tries = MAXTRIES while len(treelist) < TREECOUNT: if tries > max_tries: if VERBOSE: print("Stopping search for tree locations after {0} tries".format(tries)) print("If you don't have enough trees, check X, Y, RADIUS, and PLANTON") break tries += 1 # choose a location rad_fraction = random() # this is some kind of square interpolation rad_fraction = 1.0 - rad_fraction rad_fraction **= 2 rad_fraction = 1.0 - rad_fraction rad = rad_fraction * RADIUS ang = random() * pi * 2 x = X + int(rad * sin(ang) + .5) z = Z + int(rad * cos(ang) + .5) # check to see if this location is suitable y_top = mcmap.surface_block(x, z) if y_top is None: # this location is off the map! continue if y_top['B'] in PLANTON: # plant the tree on the block above the ground # hence the " + 1" y = y_top['y'] + 1 else: continue # this is linear interpolation also. base_height = CENTERHEIGHT + (in_out_dif * rad_fraction) height_rand = (random() - .5) * 2 * HEIGHTVARIATION height = int(base_height + height_rand) # if the option is set, check the surrounding area for trees if ONLYINFORESTS: '''we are looking for foliage it should show up in the "surface_block" search check every fifth block in a square pattern, offset around the trunk and equal to the trees height if the area is not at least one third foliage, don't build the tree''' # spacing is how far apart each sample should be spacing = 5 # search_size is how many blocks to check # along each axis search_size = 2 + (height // spacing) # check at least 3 x 3 search_size = max([search_size, 3]) # set up the offset values to offset the starting corner offset = ((search_size - 1) * spacing) // 2 # foliage_count is the total number of foliage blocks found foliage_count = 0 # check each sample location for foliage for step_x in range(search_size): # search_x is the x location to search this sample search_x = x - offset + (step_x * spacing) for step_z in range(search_size): # same as for search_x search_z = z - offset + (step_z * spacing) search_block = mcmap.surface_block(search_x, search_z) if search_block is None: continue if search_block['B'] == 18: # this sample contains foliage! # add it to the total foliage_count += 1 #now that we have the total count, find the ratio total_searched = search_size ** 2 foliage_ratio = foliage_count / total_searched # the acceptable amount is about a third acceptable_ratio = .3 if foliage_ratio < acceptable_ratio: # after all that work, there wasn't enough foliage around! # try again! continue # generate the new tree newtree = Tree([x, y, z], height) if VERBOSE: print(x, y, z, height) treelist += [newtree] def processtrees(mcmap, treelist): '''Initalize all of the trees in treelist. Set all of the trees to the right type, and run prepare. If indicated limit the height of the trees to the top of the map. ''' assert isinstance(mcmap, mcInterface.SaveFile) if SHAPE == "stickly": shape_choices = ["normal", "bamboo", "palm"] elif SHAPE == "procedural": shape_choices = ["round", "cone"] else: shape_choices = [SHAPE] # initialize mapheight, just in case mapheight = 255 for i in range(len(treelist)): newshape = choice(shape_choices) if newshape == "normal": newtree = NormalTree() elif newshape == "bamboo": newtree = BambooTree() elif newshape == "palm": newtree = PalmTree() elif newshape == "round": newtree = RoundTree() elif newshape == "cone": newtree = ConeTree() elif newshape == "rainforest": newtree = RainforestTree() elif newshape == "mangrove": newtree = MangroveTree() # Get the height and position of the existing trees in # the list. newtree.copy(treelist[i]) # Now check each tree to ensure that it doesn't stick # out the top of the map. If it does, shorten it until # the top of the foliage just touches the top of the map. if MAPHEIGHTLIMIT: height = newtree.height ybase = newtree.pos[1] if SHAPE == "rainforest": foliageheight = 2 else: foliageheight = 4 if ybase + height + foliageheight > mapheight: newheight = mapheight - ybase - foliageheight newtree.height = newheight # Even if it sticks out the top of the map, every tree # should be at least one unit tall. if newtree.height < 1: newtree.height = 1 newtree.prepare(mcmap) treelist[i] = newtree def main(the_map): '''create the trees ''' treelist = [] if VERBOSE: print("Planting new trees") planttrees(the_map, treelist) if VERBOSE: print("Processing tree changes") processtrees(the_map, treelist) if FOLIAGE: if VERBOSE: print("Generating foliage ") for i in treelist: i.makefoliage(the_map) if VERBOSE: print(' completed') if WOOD: if VERBOSE: print("Generating trunks, roots, and branches ") for i in treelist: i.maketrunk(the_map) if VERBOSE: print(' completed') return None def standalone(): if VERBOSE: print("Importing the map") try: the_map = mcInterface.SaveFile(LOADNAME) except IOError: if VERBOSE: print('File name invalid or save file otherwise corrupted. Aborting') return None main(the_map) if LIGHTINGFIX: if VERBOSE: print("Rough re-lighting the map") relight_master.save_file = the_map relight_master.calc_lighting() if VERBOSE: print("Saving the map, this could be a while") the_map.write() if VERBOSE: print("finished") if __name__ == '__main__': standalone() # to do: # get height limits from map # set "limit height" or somesuch to respect level height limits
51,634
37.163341
89
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/colorwires.py
def perform(level, box, options): groups = RedstoneGroups(level) for x in xrange(box.minx, box.maxx): for y in xrange(box.miny, box.maxy): for z in xrange(box.minz, box.maxz): groups.testblock((x, y, z)) groups.changeBlocks() TransparentBlocks = [0, 6, 8, 9, 10, 11, 18, 20, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 44, 46, 50, 51, 52, 53, 54, 55, 59, 60, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 75, 76, 77, 78, 79, 81, 83, 85, 89, 90, 92, 93, 94, 95, 96, 97, 101, 102, 104, 105, 106, 107, 108, 109, 111, 113, 114, 115, 116, 117, 118, 119, 120, 122, 126, 127] class RedstoneGroups: group = {} currentgroup = 0 def __init__(self, level): self.level = level @staticmethod def isRedstone(blockid): return blockid == 55 or blockid == 93 or blockid == 94 def testblock(self, pos): (x, y, z) = pos blockid = self.level.blockAt(x, y, z) if self.isRedstone(blockid): if (x, y, z) in self.group: return self.group[pos] = self.currentgroup self.testneighbors(pos) self.currentgroup += 1 def testneighbors(self, (x, y, z)): for dy in xrange(-1, 2, 1): if 0 <= dy + y + dy <= 255: self.testneighbor((x, y, z), (x - 1, y + dy, z)) self.testneighbor((x, y, z), (x + 1, y + dy, z)) self.testneighbor((x, y, z), (x, y + dy, z - 1)) self.testneighbor((x, y, z), (x, y + dy, z + 1)) def testneighbor(self, pos1, pos2): if pos2 in self.group: return if self.connected(pos1, pos2): self.group[pos2] = self.currentgroup self.testneighbors(pos2) def getBlockAt(self, (x, y, z)): return self.level.blockAt(x, y, z) def repeaterAlignedWith(self, (x1, y1, z1), (x2, y2, z2)): blockid = self.getBlockAt((x1, y1, z1)) if blockid != 93 and blockid != 94: return False direction = self.level.blockDataAt(x1, y1, z1) % 4 if (direction == 0 or direction == 2) and abs(z2 - z1) != 1: return False elif (direction == 1 or direction == 3) and abs(x2 - x1) != 1: return False return True def repeaterPointingTowards(self, (x1, y1, z1), (x2, y2, z2)): blockid = self.getBlockAt((x1, y1, z1)) if blockid != 93 and blockid != 94: return False direction = self.level.blockDataAt(x1, y1, z1) % 4 if direction == 0 and z2 - z1 == -1: return True if direction == 1 and x2 - x1 == 1: return True if direction == 2 and z2 - z1 == 1: return True if direction == 3 and x2 - x1 == -1: return True return False def repeaterPointingAway(self, (x1, y1, z1), (x2, y2, z2)): blockid = self.getBlockAt((x1, y1, z1)) if blockid != 93 and blockid != 94: return False direction = self.level.blockDataAt(x1, y1, z1) % 4 if direction == 0 and z2 - z1 == 1: return True if direction == 1 and x2 - x1 == -1: return True if direction == 2 and z2 - z1 == -1: return True if direction == 3 and x2 - x1 == 1: return True return False def connected(self, (x1, y1, z1), (x2, y2, z2)): blockid1 = self.level.blockAt(x1, y1, z1) blockid2 = self.level.blockAt(x2, y2, z2) pos1 = (x1, y1, z1) pos2 = (x2, y2, z2) if y1 == y2: if blockid1 == 55: if blockid2 == 55: return True elif self.repeaterAlignedWith(pos2, pos1): return True elif self.repeaterAlignedWith(pos1, pos2) and blockid2 == 55: return True elif self.repeaterPointingTowards(pos1, pos2) and self.repeaterPointingAway(pos2, pos1): return True elif self.repeaterPointingAway(pos1, pos2) and self.repeaterPointingTowards(pos2, pos1): return True elif y2 == y1 - 1: aboveid = self.level.blockAt(x2, y2 + 1, z2) if blockid1 == 55: if blockid2 == 55 and TransparentBlocks.count(aboveid) == 1: return True elif self.repeaterAlignedWith(pos2, pos1): return True elif self.repeaterPointingTowards(pos1, pos2): if blockid2 == 55 and TransparentBlocks.count(aboveid) == 0: return True elif y2 == y1 + 1: return self.connected(pos2, pos1) return False SkipBlocks = [23, 61, 62, 89] def changeBlocks(self): for ((x, y, z), gr) in self.group.items(): if y > 0: blockid = self.level.blockAt(x, y - 1, z) if self.SkipBlocks.count(blockid) == 1: continue self.level.setBlockAt(x, y - 1, z, 35) self.level.setBlockDataAt(x, y - 1, z, gr % 16) self.level.getChunk(x / 16, z / 16).dirty = True
5,274
33.253247
120
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/test_.py
from pymclevel.materials import BlockstateAPI from pymclevel import nbt import numpy def perform(level, box, options): block_api = level.materials.blockstate_api assert isinstance(block_api, BlockstateAPI) print block_api.idToBlockstate(251, 1) root = nbt.TAG_Compound() data = nbt.TAG_Compound() iarray = nbt.TAG_Int_Array() data['test1'] = iarray #array = nbt.TAG_Long_Array() #root['test'] = array root['data'] = data print root root.save('test.nbt')
509
20.25
47
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/demo/Test.py
from albow import Widget, Label, Button, TextFieldWrapped from pymclevel.nbt import * import release operations = { "Yes/No Dialog": 1, "Custom Dialog": 2, "Scoreboard Editing (Objective)": 3, "Scoreboard Editing (Team)": 4, "Player Data": 5, } inputs = ( ("Operation", tuple(sorted(operations.keys()))), ("Float Field Test (Default)", 0.0), ("Float Field Test (Min=-1.0 Max=1.0", (0.0, -1.0, 1.0)), ("Float Field Test (Increments by 0.3)", (0.0, -5.0, 5.0, 0.3)), ) class StoreData: def __init__(self): self._isFork = False self._editor = None @property def isFork(self): return self._isFork @property def editor(self): return self._editor data = StoreData() def hiAction(): print '"Hi" Button clicked!' def yesFUNC(level, box): for x in xrange(box.minx, box.maxx): for y in xrange(box.miny, box.maxy): for z in xrange(box.minz, box.maxz): level.setBlockAt(x, y, z, 19) def perform(level, box, options): ver = release.get_version() if "unified" in ver.lower(): try: data.editor = editor data.isFork = True except NameError: import inspect data.editor = inspect.stack()[1][0].f_locals.get('self', None).editor pass else: import inspect data.editor = inspect.stack()[1][0].f_locals.get('self', None).editor if not data.isFork: raise NotImplemented("This filter will only work with MCEdit-Unified!") op = options["Operation"] #print dir(level.scoreboard.Objectives) #print level.init_scoreboard().PlayerScores["Chevalerie94"] print "Test Filter Ran" if op == "Yes/No Dialog": choice = editor.YesNoWidget("Place a sponge block here?") if choice: yesFunc(level, box) raise Exception("Response was Yes") else: raise Exception("Response was No") elif op == "Custom Dialog": entities = {} chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x,y,z) in box: keyname = "{0} - {1},{2},{3}".format(e["id"].value,int(x),int(y),int(z)) entities[keyname] = e chunks.append(chunk) thing = ( ("Entity", tuple(sorted(entities.keys()))), ("Entity Name", "string"), ("Replace existing names?", False), ) result = editor.addExternalWidget(thing) if result != "user canceled": entity = entities[result["Entity"]] if "CustomName" not in result["Entity"]: entity["CustomName"] = TAG_String(result["Entity Name"]) elif "CustomName" in result["Entity"] and result["Replace existing names?"]: result["Entity"]["CustomName"] = TAG_String(result["Entity Name"]) for c in chunks: c.dirty = True elif op == "Scoreboard Editing (Objective)": scoreboard = level.init_scoreboard() test_objective = TAG_Compound() test_objective["Name"] = TAG_String("FilterObjective") test_objective["DisplayName"] = TAG_String("FilterObjective") test_objective["CriteriaName"] = TAG_String("dummy") test_objective["RenderType"] = TAG_String("integer") scoreboard["data"]["Objectives"].append(test_objective) level.save_scoreboard(scorebaord) for objective in score.Objectives: print "Objective Name: " + str(objective["Name"].value) elif op == "Scoreboard Editing (Team)": if level.scoreboard is not None: for team in level.scoreboard.Teams: print "Team Name: " + str(team.DisplayName) elif op == "Player Data": players = level.init_player_data() for p in players.keys(): print players[p]["Air"].value level.save_player_data(players)
4,177
35.017241
92
py
MCEdit-Unified
MCEdit-Unified-master/stock-filters/demo/filterdemo.py
# the inputs list tells MCEdit what kind of options to present to the user. # each item is a (name, value) pair. name is a text string acting # both as a text label for the input on-screen and a key for the 'options' # parameter to perform(). value and its type indicate allowable and # default values for the option: # True or False: creates a checkbox with the given value as default # int or float value: creates a value input with the given value as default # int values create fields that only accept integers. # tuple of numbers: a tuple of ints or floats creates a value input with minimum and # maximum values. a 2-tuple specifies (min, max) with min as default. # a 3-tuple specifies (default, min, max) # tuple of strings: a tuple of strings creates a popup menu whose entries are # labeled with the given strings. the first item in the tuple is selected # by default. returns one of the strings in the tuple. # "blocktype" as a string: creates a button the user can click to choose # a block type in a list. returns a Block object. the object has 'ID' # and 'blockData' attributes. # this dictionary creates an integer input with range (-128, 128) and default 4, # a blocktype picker, a floating-point input with no limits and default 15.0, # a checkbox initially checked, and a menu of choices displayName = "Test Filter" inputs = ( ("Depth", (4, -128, 128)), ("Pick a block:", "blocktype"), ("Fractal complexity", 15.0), ("Enable thrusters", True), ("Access method", ("Use blockAt", "Use temp schematic", "Use chunk slices")), ) # perform() is the main entry point of a filter. Its parameters are # a MCLevel instance, a BoundingBox, and an options dictionary. # The options dictionary will have keys corresponding to the keys specified above, # and values reflecting the user's input. # you get undo for free: everything within 'box' is copied to a temporary buffer # before perform is called, and then copied back when the user asks to undo def perform(level, box, options): if options["Enable thrusters"]: # Errors will alert the user and print a traceback to the console. raise NotImplementedError("Thrusters not attached!") method = options["Access method"] # There are a few general ways of accessing a level's blocks # The first is using level.blockAt and level.setBlockAt # These are slower than the other two methods, but easier to start using if method == "Use blockAt": for x in xrange(box.minx, box.maxx): for z in xrange(box.minz, box.maxz): for y in xrange(box.miny, box.maxy): # nested loops can be slow # replaces gold with TNT. straightforward. if level.blockAt(x, y, z) == 14: level.setBlockAt(x, y, z, 46) # The second is to extract the segment of interest into a contiguous array # using level.extractSchematic. this simplifies using numpy but at the cost # of the temporary buffer and the risk of a memory error on 32-bit systems. if method == "Use temp schematic": temp = level.extractSchematic(box) # remove any entities in the temp. this is an ugly move # because copyBlocksFrom actually copies blocks, entities, everything temp.removeEntitiesInBox(temp.bounds) temp.removeTileEntitiesInBox(temp.bounds) # replaces gold with TNT. # the expression in [] creates a temporary the same size, using more memory temp.Blocks[temp.Blocks == 14] = 46 level.copyBlocksFrom(temp, temp.bounds, box.origin) # The third method iterates over each subslice of every chunk in the area # using level.getChunkSlices. this method is a bit arcane, but lets you # visit the affected area chunk by chunk without using too much memory. if method == "Use chunk slices": for (chunk, slices, point) in level.getChunkSlices(box): # chunk is an AnvilChunk object with attributes: # Blocks, Data, Entities, and TileEntities # Blocks and Data can be indexed using slices: blocks = chunk.Blocks[slices] # blocks now contains a "view" on the part of the chunk's blocks # that lie in the selection. This "view" is a numpy object that # accesses only a subsection of the original array, without copying # once again, gold into TNT blocks[blocks == 14] = 46 # notify the world that the chunk changed # this gives finer control over which chunks are dirtied # you can call chunk.chunkChanged(False) if you want to dirty it # but not run the lighting calc later. chunk.chunkChanged() # You can also access the level any way you want # Beware though, you only get to undo the area within the specified box pos = level.getPlayerPosition() cpos = int(pos[0]) >> 4, int(pos[2]) >> 4 chunk = level.getChunk(*cpos) chunk.Blocks[::4, ::4, :64] = 46 # replace every 4x4th column of land with TNT
5,141
44.910714
87
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Paste.py
from pymclevel.materials import Block from editortools.brush import createBrushMask import mcplatform import pymclevel from pymclevel import BoundingBox displayName = 'Schematic' addPasteButton = True disableStyleButton = True def createInputs(self): self.inputs= ( ) pass def createDirtyBox(self, point, tool): newpoint = [] for p in point: newpoint.append(p-1) return BoundingBox(newpoint, tool.level.size) def apply(self, op, point): level = op.tool.level newpoint = [] for p in point: newpoint.append(p-1) return op.level.copyBlocksFromIter(level, level.bounds, newpoint, create=True)
669
20.612903
82
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Erode.py
from pymclevel.materials import Block from editortools.brush import createBrushMask import numpy displayName = 'Erode' def createInputs(self): self.inputs = ( {'Hollow': False}, {'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Strength': (1, 1, 20)}, {'Old (Messy)': False}, {'Minimum Spacing': 1} ) def apply(self, op, point): brushBox = op.tool.getDirtyBox(point, op.tool).expand(1) if brushBox.volume > 1048576: print "Affected area is too big for this brush mode" return erosionStrength = op.options["Strength"] erosionArea = op.level.extractSchematic(brushBox, entities=False) if erosionArea is None: return blocks = erosionArea.Blocks data = erosionArea.Data bins = numpy.bincount(blocks.ravel()) fillBlockID = bins.argmax() xcount = -1 for _ in blocks: xcount += 1 ycount = -1 for _ in blocks[xcount]: ycount += 1 zcount = -1 for _ in blocks[xcount][ycount]: zcount += 1 if blocks[xcount][ycount][zcount] == fillBlockID: fillBlockData = data[xcount][ycount][zcount] def getNeighbors(solidBlocks): neighbors = numpy.zeros(solidBlocks.shape, dtype='uint8') neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[:-2, 1:-1, 1:-1] neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[2:, 1:-1, 1:-1] neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[1:-1, :-2, 1:-1] neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[1:-1, 2:, 1:-1] neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[1:-1, 1:-1, :-2] neighbors[1:-1, 1:-1, 1:-1] += solidBlocks[1:-1, 1:-1, 2:] return neighbors for i in range(erosionStrength): solidBlocks = blocks != 0 neighbors = getNeighbors(solidBlocks) brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style']) erodeBlocks = neighbors < 5 if op.options['Old (Messy)']: erodeBlocks &= (numpy.random.random(erodeBlocks.shape) > 0.3) erodeBlocks[1:-1, 1:-1, 1:-1] &= brushMask blocks[erodeBlocks] = 0 solidBlocks = blocks != 0 neighbors = getNeighbors(solidBlocks) fillBlocks = neighbors > 2 fillBlocks &= ~solidBlocks fillBlocks[1:-1, 1:-1, 1:-1] &= brushMask blocks[fillBlocks] = fillBlockID data[fillBlocks] = fillBlockData op.level.copyBlocksFrom(erosionArea, erosionArea.bounds.expand(-1), brushBox.origin + (1, 1, 1))
2,572
31.1625
100
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Fill.py
from pymclevel.materials import Block from editortools.brush import createBrushMask, createTileEntities import numpy displayName = 'Fill' mainBlock = 'Block' def createInputs(self): self.inputs = ( {'Hollow': False}, {'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Block': materials.blockWithID(1, 0)}, {'Fill Air': True}, {'Minimum Spacing': 1} ) def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) blocks = chunk.Blocks[slices] data = chunk.Data[slices] airFill = op.options['Fill Air'] if not airFill: airtable = numpy.zeros((materials.id_limit, 16), dtype='bool') airtable[0] = True replaceMaskAir = airtable[blocks, data] brushMask &= ~replaceMaskAir chunk.Blocks[slices][brushMask] = op.options['Block'].ID chunk.Data[slices][brushMask] = op.options['Block'].blockData createTileEntities(op.options['Block'], brushBoxThisChunk, chunk)
1,154
29.394737
155
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Topsoil.py
from editortools.brush import createBrushMask, createTileEntities from pymclevel.level import extractHeights import itertools displayName = "Topsoil" def createInputs(self): self.inputs = ( {'Hollow': False}, {'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Block': materials.blockWithID(1, 0)}, {'Depth': 1}, {'Only Change Natural Earth': False}, {'Minimum Spacing': 1}, ) def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): depth = op.options['Depth'] blocktype = op.options['Block'] blocks = chunk.Blocks[slices] data = chunk.Data[slices] brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) if op.options['Only Change Natural Earth']: try: # try to get the block mask from the topsoil filter import topsoil # @UnresolvedImport blockmask = topsoil.naturalBlockmask() blockmask[blocktype.ID] = True blocktypeMask = blockmask[blocks] except Exception, e: print repr(e), " while using blockmask from filters.topsoil" blocktypeMask = blocks != 0 else: # topsoil any block blocktypeMask = blocks != 0 if depth < 0: blocktypeMask &= (blocks != blocktype.ID) if len(blocktypeMask) == 0: return heightmap = extractHeights(blocktypeMask) for x, z in itertools.product(*map(xrange, heightmap.shape)): h = heightmap[x, z] if h >= brushBoxThisChunk.height: continue if depth > 0: idx = x, z, slice(max(0, h - depth), h) else: # negative depth values mean to put a layer above the surface idx = x, z, slice(h, min(blocks.shape[2], h - depth)) mask = brushMask[idx] blocks[idx][mask] = blocktype.ID data[idx][mask] = blocktype.blockData createTileEntities(blocktype, brushBoxThisChunk, chunk)
2,075
29.985075
155
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Varied Replace.py
from pymclevel.materials import Block from editortools.brush import createBrushMask, createTileEntities from albow import alert from pymclevel import block_fill import numpy import random displayName = "Varied Replace" mainBlock = "Block 1" secondaryBlock = "Block" def createInputs(self): self.inputs = ( {'Hollow': False, 'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Block': materials.blockWithID(1, 0)}, {'Block 1': materials.blockWithID(1, 0)}, {'Block 2': materials.blockWithID(1, 0)}, {'Block 3': materials.blockWithID(1, 0)}, {'Block 4': materials.blockWithID(1, 0)}, {'Weight 1': (1, 0, None), 'Weight 2': (1, 0, None)}, {'Weight 3': (1, 0, None), 'Weight 4': (1, 0, None)}, {'Minimum Spacing': 1}, ) def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) replaceWith1 = op.options['Block 1'] chanceA = op.options['Weight 1'] replaceWith2 = op.options['Block 2'] chanceB = op.options['Weight 2'] replaceWith3 = op.options['Block 3'] chanceC = op.options['Weight 3'] replaceWith4 = op.options['Block 4'] chanceD = op.options['Weight 4'] totalChance = chanceA + chanceB + chanceC + chanceD if totalChance == 0: print "Total Chance value can't be 0." return blocks = chunk.Blocks[slices] data = chunk.Data[slices] if op.options['Block'].wildcard: print "Wildcard replace" blocksToReplace = [] for i in range(16): blocksToReplace.append(op.editor.level.materials.blockWithID(op.options['Block'].ID, i)) else: blocksToReplace = [op.options['Block']] replaceTable = block_fill.blockReplaceTable(blocksToReplace) replaceMask = replaceTable[blocks, data] brushMask &= replaceMask brushMaskOption1 = numpy.copy(brushMask) brushMaskOption2 = numpy.copy(brushMask) brushMaskOption3 = numpy.copy(brushMask) brushMaskOption4 = numpy.copy(brushMask) x = -1 for _ in brushMask: x += 1 y = -1 for _ in brushMask[x]: y += 1 z = -1 for _ in brushMask[x][y]: z += 1 if brushMask[x][y][z]: randomChance = random.randint(1, totalChance) if chanceA >= randomChance: brushMaskOption1[x][y][z] = True brushMaskOption2[x][y][z] = False brushMaskOption3[x][y][z] = False brushMaskOption4[x][y][z] = False continue if chanceA + chanceB >= randomChance: brushMaskOption1[x][y][z] = False brushMaskOption2[x][y][z] = True brushMaskOption3[x][y][z] = False brushMaskOption4[x][y][z] = False continue if chanceA + chanceB + chanceC >= randomChance: brushMaskOption1[x][y][z] = False brushMaskOption2[x][y][z] = False brushMaskOption3[x][y][z] = True brushMaskOption4[x][y][z] = False continue if chanceA + chanceB + chanceC + chanceD >= randomChance: brushMaskOption1[x][y][z] = False brushMaskOption2[x][y][z] = False brushMaskOption3[x][y][z] = False brushMaskOption4[x][y][z] = True continue blocks[brushMaskOption1] = replaceWith1.ID data[brushMaskOption1] = replaceWith1.blockData blocks[brushMaskOption2] = replaceWith2.ID data[brushMaskOption2] = replaceWith2.blockData blocks[brushMaskOption3] = replaceWith3.ID data[brushMaskOption3] = replaceWith3.blockData blocks[brushMaskOption4] = replaceWith4.ID data[brushMaskOption4] = replaceWith4.blockData UsedAlready = [] createTileEntities(replaceWith1, brushBoxThisChunk, chunk) UsedAlready.append(replaceWith1.ID) if replaceWith2.ID not in UsedAlready: createTileEntities(replaceWith2, brushBoxThisChunk, chunk) UsedAlready.append(replaceWith2.ID) if replaceWith3.ID not in UsedAlready: createTileEntities(replaceWith3, brushBoxThisChunk, chunk) UsedAlready.append(replaceWith3.ID) if replaceWith4.ID not in UsedAlready: createTileEntities(replaceWith4, brushBoxThisChunk, chunk)
4,708
37.284553
155
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Replace.py
from pymclevel.materials import Block from editortools.brush import createBrushMask, createTileEntities from pymclevel import block_fill displayName = 'Replace' mainBlock = 'Block To Replace With' secondaryBlock = 'Block' wildcardBlocks = ['Block'] def createInputs(self): self.inputs = ( {'Hollow': False}, {'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Block': materials.blockWithID(1, 0)}, {'Block To Replace With': materials.blockWithID(1, 0)}, {'Swap': tool.swap}, {'Minimum Spacing': 1} ) def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) blocks = chunk.Blocks[slices] data = chunk.Data[slices] if op.options['Block'].wildcard: print "Wildcard replace" blocksToReplace = [] for i in range(16): blocksToReplace.append(op.editor.level.materials.blockWithID(op.options['Block'].ID, i)) else: blocksToReplace = [op.options['Block']] replaceTable = block_fill.blockReplaceTable(blocksToReplace) replaceMask = replaceTable[blocks, data] brushMask &= replaceMask chunk.Blocks[slices][brushMask] = op.options['Block To Replace With'].ID chunk.Data[slices][brushMask] = op.options['Block To Replace With'].blockData createTileEntities(op.options['Block To Replace With'], brushBoxThisChunk, chunk)
1,539
33.222222
155
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Flood Fill.py
from pymclevel.materials import Block from pymclevel.entity import TileEntity from editortools.brush import createBrushMask import numpy from editortools.operation import mkundotemp from albow import showProgress import pymclevel import datetime import collections from pymclevel import BoundingBox import logging log = logging.getLogger(__name__) displayName = 'Flood Fill' disableStyleButton = True def createInputs(self): self.inputs = ( {'Block': materials.blockWithID(1, 0)}, {'Indiscriminate': False}, ) def createTileEntities(tileEntityTag, level): x, y, z = TileEntity.pos(tileEntityTag) try: chunk = level.getChunk(x >> 4, z >> 4) except (pymclevel.ChunkNotPresent, pymclevel.ChunkMalformed): return chunk.TileEntities.append(tileEntityTag) chunk._fakeEntities = None def apply(self, op, point): # undoLevel = pymclevel.MCInfdevOldLevel(mkundotemp(), create=True) # Use the same world as the one loaded. create = True if op.level.gamePlatform == 'PE': create = op.level.world_version undoLevel = type(op.level)(mkundotemp(), create=create) if op.level.gamePlatform == 'PE': undoLevel.Height = op.level.Height dirtyChunks = set() def saveUndoChunk(cx, cz): if (cx, cz) in dirtyChunks: return dirtyChunks.add((cx, cz)) undoLevel.copyChunkFrom(op.level, cx, cz) doomedBlock = op.level.blockAt(*point) doomedBlockData = op.level.blockDataAt(*point) checkData = (doomedBlock not in (8, 9, 10, 11)) indiscriminate = op.options['Indiscriminate'] if indiscriminate: checkData = False if doomedBlock == 2: # grass doomedBlock = 3 # dirt if doomedBlock == op.options['Block'].ID and (doomedBlockData == op.options['Block'].blockData or not checkData): return tileEntity = None if op.options['Block'].stringID in TileEntity.stringNames.keys(): tileEntity = TileEntity.stringNames[op.options['Block'].stringID] x, y, z = point saveUndoChunk(x // 16, z // 16) op.level.setBlockAt(x, y, z, op.options['Block'].ID) op.level.setBlockDataAt(x, y, z, op.options['Block'].blockData) if tileEntity: if op.level.tileEntityAt(x, y, z): op.level.removeTileEntitiesInBox(BoundingBox((x, y, z), (1, 1, 1))) tileEntityObject = TileEntity.Create(tileEntity, (x, y, z), defsIds=op.level.defsIds) createTileEntities(tileEntityObject, op.level) def processCoords(coords): newcoords = collections.deque() for (x, y, z) in coords: for _dir, offsets in pymclevel.faceDirections: dx, dy, dz = offsets p = (x + dx, y + dy, z + dz) nx, ny, nz = p b = op.level.blockAt(nx, ny, nz) if indiscriminate: if b == 2: b = 3 if b == doomedBlock: if checkData: if op.level.blockDataAt(nx, ny, nz) != doomedBlockData: continue saveUndoChunk(nx // 16, nz // 16) op.level.setBlockAt(nx, ny, nz, op.options['Block'].ID) op.level.setBlockDataAt(nx, ny, nz, op.options['Block'].blockData) if tileEntity: if op.level.tileEntityAt(nx, ny, nz): op.level.removeTileEntitiesInBox(BoundingBox((nx, ny, nz), (1, 1, 1))) tileEntityObject = TileEntity.Create(tileEntity, (nx, ny, nz)) createTileEntities(tileEntityObject, op.level) newcoords.append(p) return newcoords def spread(coords): while len(coords): start = datetime.datetime.now() num = len(coords) coords = processCoords(coords) d = datetime.datetime.now() - start progress = "Did {0} coords in {1}".format(num, d) log.info(progress) yield progress showProgress("Flood fill...", spread([point]), cancel=True) op.editor.invalidateChunks(dirtyChunks) op.undoLevel = undoLevel
4,233
33.422764
117
py
MCEdit-Unified
MCEdit-Unified-master/stock-brushes/Varied Fill.py
from pymclevel.materials import Block from editortools.brush import createBrushMask, createTileEntities from albow import alert import numpy import random displayName = "Varied Fill" mainBlock = "Block 1" secondaryBlock = "Block" def createInputs(self): self.inputs = ( {'Hollow': False, 'Noise': 100}, {'W': (3, 1, 4096), 'H': (3, 1, 4096), 'L': (3, 1, 4096)}, {'Block 1': materials.blockWithID(1, 0)}, {'Block 2': materials.blockWithID(1, 0)}, {'Block 3': materials.blockWithID(1, 0)}, {'Block 4': materials.blockWithID(1, 0)}, {'Weight 1': (1, 0, None), 'Weight 2': (1, 0, None)}, {'Weight 3': (1, 0, None), 'Weight 4': (1, 0, None)}, {'Minimum Spacing': 1}, {'Fill Air': True}, ) def applyToChunkSlices(self, op, chunk, slices, brushBox, brushBoxThisChunk): brushMask = createBrushMask(op.tool.getBrushSize(), op.options['Style'], brushBox.origin, brushBoxThisChunk, op.options['Noise'], op.options['Hollow']) blocks = chunk.Blocks[slices] data = chunk.Data[slices] airFill = op.options['Fill Air'] replaceWith1 = op.options['Block 1'] chanceA = op.options['Weight 1'] replaceWith2 = op.options['Block 2'] chanceB = op.options['Weight 2'] replaceWith3 = op.options['Block 3'] chanceC = op.options['Weight 3'] replaceWith4 = op.options['Block 4'] chanceD = op.options['Weight 4'] totalChance = chanceA + chanceB + chanceC + chanceD if totalChance == 0: print "Total Chance value can't be 0." return if not airFill: airtable = numpy.zeros((materials.id_limit, 16), dtype='bool') airtable[0] = True replaceMaskAir = airtable[blocks, data] brushMask &= ~replaceMaskAir brushMaskOption1 = numpy.copy(brushMask) brushMaskOption2 = numpy.copy(brushMask) brushMaskOption3 = numpy.copy(brushMask) brushMaskOption4 = numpy.copy(brushMask) x = -1 for _ in brushMask: x += 1 y = -1 for _ in brushMask[x]: y += 1 z = -1 for _ in brushMask[x][y]: z += 1 if brushMask[x][y][z]: randomChance = random.randint(1, totalChance) if chanceA >= randomChance: brushMaskOption1[x][y][z] = True brushMaskOption2[x][y][z] = False brushMaskOption3[x][y][z] = False brushMaskOption4[x][y][z] = False continue if chanceA + chanceB >= randomChance: brushMaskOption1[x][y][z] = False brushMaskOption2[x][y][z] = True brushMaskOption3[x][y][z] = False brushMaskOption4[x][y][z] = False continue if chanceA + chanceB + chanceC >= randomChance: brushMaskOption1[x][y][z] = False brushMaskOption2[x][y][z] = False brushMaskOption3[x][y][z] = True brushMaskOption4[x][y][z] = False continue if chanceA + chanceB + chanceC + chanceD >= randomChance: brushMaskOption1[x][y][z] = False brushMaskOption2[x][y][z] = False brushMaskOption3[x][y][z] = False brushMaskOption4[x][y][z] = True continue blocks[brushMaskOption1] = replaceWith1.ID data[brushMaskOption1] = replaceWith1.blockData blocks[brushMaskOption2] = replaceWith2.ID data[brushMaskOption2] = replaceWith2.blockData blocks[brushMaskOption3] = replaceWith3.ID data[brushMaskOption3] = replaceWith3.blockData blocks[brushMaskOption4] = replaceWith4.ID data[brushMaskOption4] = replaceWith4.blockData UsedAlready = [] createTileEntities(replaceWith1, brushBoxThisChunk, chunk) UsedAlready.append(replaceWith1.ID) if replaceWith2.ID not in UsedAlready: createTileEntities(replaceWith2, brushBoxThisChunk, chunk) UsedAlready.append(replaceWith2.ID) if replaceWith3.ID not in UsedAlready: createTileEntities(replaceWith3, brushBoxThisChunk, chunk) UsedAlready.append(replaceWith3.ID) if replaceWith4.ID not in UsedAlready: createTileEntities(replaceWith4, brushBoxThisChunk, chunk)
4,466
37.179487
155
py
MCEdit-Unified
MCEdit-Unified-master/leveldb_mcpe/test.py
exceptions = 0 from leveldb_mcpe import DB, Options, ReadOptions, WriteOptions, WriteBatch, RepairWrapper op = Options() op.create_if_missing = True wop = WriteOptions() rop = ReadOptions() db = DB(op, "test") db.Put(wop, "1", "5") db.Put(wop, "2", "6") if db.Get(rop, "1") != "5": print "Failed to retrieve correct value for key '1'. Expected '5', got: '{0}'".format(db.Get(rop, "1")) exceptions += 1 db.Delete(wop, "2") try: db.Get(rop, "2") print "Failed to delete a value from the database" exceptions += 1 except: # Maybe add a test for just the NoValue exception? pass db.Put(wop, "3", "5") db.Put(wop, "4", "6") value1 = db.Get(rop, "3") batch = WriteBatch() batch.Delete("3") batch.Put("4", "5") db.Write(wop, batch) del batch try: db.Get(rop, "3") print "Failed to delete a value using WriteBatch" exceptions += 1 except: pass if db.Get(rop, "4") != "5": print "Failed to write a value using WriteBatch" exceptions += 1 try: it = db.NewIterator(rop) it.SeekToFirst() while it.Valid(): it.Next() it.status() # Possible errors are handled by C++ side del it except: print "Failed to iterate over database" exceptions += 1 try: db.Put(wop, "a", "old") db.Put(wop, "b", "old") snapshot = db.GetSnapshot() ropSnapshot = ReadOptions() ropSnapshot.snapshot = snapshot db.Put(wop, "a", "new") db.Put(wop, "b", "new") snapIt = db.NewIterator(ropSnapshot) newIt = db.NewIterator(rop) snapIt.SeekToFirst() newIt.SeekToFirst() while snapIt.Valid(): if snapIt.key() in ("a", "b") and snapIt.value() != "old": print "Failed to retrieve correct value from database after creating a snapshot." exceptions += 1 snapIt.Next() while newIt.Valid(): if newIt.key() in ("a", "b") and newIt.value() != "new": print "Failed to retrieve correct value from database after creating a snapshot." exceptions += 1 newIt.Next() del newIt, snapIt except: print "Failed to test snapshots" exceptions += 1 db.ReleaseSnapshot(snapshot) del db RepairWrapper('test', op) if exceptions > 0: print " {0} tests failed".format(exceptions) else: print "Successfully completed test."
2,307
22.313131
107
py
MCEdit-Unified
MCEdit-Unified-master/leveldb_mcpe/setup.py
from setuptools import setup from distutils.extension import Extension import os.path import sys extra_compile_args = ["-DDLLX="] extra_link_args = [] define_macros = [] runtime_library_dirs = [] library_dirs = [] libraries = [] include_dirs = [] if sys.platform == "win32": if sys.maxsize > 2 ** 32: # 64-bit print "Building windows application 'leveldb_mcpe' x64" include_dirs = ["C:/Boost/include/boost-1_55", "./leveldb-mcpe/include"] library_dirs = ["C:/Boost/lib/x64", "."] libraries = ["leveldb-mcpe", "shell32", "zlib"] extra_compile_args += ["/EHs", "/MD"] extra_link_args += ["/MACHINE:x64", "/NODEFAULTLIB:LIBCMT"] define_macros = [("WIN32", None), ("_WINDOWS", None), ("LEVELDB_PLATFORM_WINDOWS", None), ("OS_WIN", None)] else: # 32-bit print "Building windows application 'leveldb_mcpe' x32" include_dirs = ["C:/Boost/include/boost-1_55", "./leveldb-mcpe/include"] library_dirs = ["C:/Boost/lib/i386", "."] libraries = ["leveldb-mcpe", "shell32", "zlib"] extra_compile_args += ["/EHs", "/MD"] extra_link_args += ["/MACHINE:x86", "/NODEFAULTLIB:LIBCMT"] define_macros = [("WIN32", None), ("_WINDOWS", None), ("LEVELDB_PLATFORM_WINDOWS", None), ("OS_WIN", None)] elif sys.platform == "darwin": include_dirs = ["/usr/local/include/boost", "./leveldb-mcpe/include", "."] library_dirs = ["/usr/local/lib", ".", "./leveldb-mcpe"] libraries = ["boost_python", "leveldb"] elif sys.platform == "linux2": import platform if sys.argv[-1] == 'setup.py': print 'No command specified. Aborting.' print 'Please, use `python setup.py build` to build Pocket Edition support for MCEdit.' sys.exit(1) print "Building Linux application 'leveldb_mcpe'..." # TODO: add checks, warnings and recomandations if something fails... (<< On the way) # add a cleanup option # make this part a separate file # First, unpack and build dependencies: boost and mojang's leveldb-mcpe # Need make, g++, tar, unzip, Python 2.7 header files # boost will be installed there to avoid elevation problems # 'build_ext --inplace' is not wanted here. Let it be replaced with build if '--inplace' in sys.argv: sys.argv.remove('--inplace') if 'build_ext' in sys.argv: sys.argv.remove('build_ext') sys.argv.append('build') curdir = os.getcwd() destpath = '../pymclevel' # Check if leveldb_mcpe is already built if (not os.system('ls -R build/*/leveldb_mcpe.so > /dev/null')) or os.path.exists(os.path.join(destpath, 'leveldb_mcpe.so')): a =raw_input('The library is already present. Do you want to recompile [y/N]?') if a and a in 'yY': if os.path.exists('build'): os.system('rm -R build') if os.path.exists(os.path.join(destpath, 'leveldb_mcpe.so')): os.system('rm %s'%os.path.join(destpath, 'leveldb_mcpe.so')) else: print 'Exiting.' sys.exit(0) # Check if the user library directory exists user_libdir = os.path.expanduser('~/.local/lib') if not os.path.exists(user_libdir): print 'Creating needed library folder: %s' % user_libdir os.makedirs(user_libdir) print 'Done' # Set the definitive Mojang's leveldb-mcpe lib directory to the user's one mcpeso_dir = os.path.join(user_libdir, 'leveldb-mcpe') # Check and install Boost boost_version = '1.58.0' boostRoot = os.path.expanduser('~/.local/lib/boost_%s_mcpe'%boost_version.replace('.', '_')) install_boost = None build_boost_python = None if not os.path.exists(boostRoot): install_boost = True else: a = raw_input('Boost found in %s.\nDo you want to reinstall it [y/N]?' % boostRoot) if a and a in 'yY': install_boost = True else: install_boost = False if not os.path.exists(os.path.join(boostRoot, 'stage', 'lib', 'libboost_python.a')): build_boost_python = True else: a = raw_input('Boost Python wrapper found in %s.\nDo you want to rebuild it [y/N]?' % os.path.join(boostRoot, 'stage', 'lib')) if a and a in 'yY': build_boost_python = True else: build_boost_python = False if install_boost is None: # Shall not happen... print 'Impossible to determine if Boost %s is installed in your personnal library folder.'%boost_version a = raw_input('Do you want to (re)install it [y/N] ?') if a and a in 'yY': install_boost = True if build_boost_python is None: # Shall not happen... print 'Impossible to determine if Boost Python wrapper is installed in your personnal library folder.' a = raw_input('Do you want to (re)install it [y/N] ?') if a and a in 'yY': build_boost_python = True if install_boost: print "Dowloading Boost %s from SourceForge..."%boost_version os.system('wget http://freefr.dl.sourceforge.net/project/boost/boost/%s/boost_%s.tar.bz2'%(boost_version, boost_version.replace('.', '_'))) print "Extracting boost..." os.system('tar --bzip2 -xf boost_%s.tar.bz2'%boost_version.replace('.', '_')) os.system('mv boost_%s %s' % (boost_version.replace('.', '_'), boostRoot)) os.chdir(boostRoot) print "Installing boost..." os.system('sh ./bootstrap.sh --prefix=%s' % boostRoot) os.chdir(curdir) print 'Done.' if build_boost_python: print "Building boost_python..." os.chdir(boostRoot) os.system('./b2 --with-python --prefix=%s --build-dir=%s -a link=static cxxflags="-fPIC" linkflags="-fPIC"' % ( boostRoot, boostRoot)) os.chdir(curdir) print 'Done.' # Unpack and build leveldb-mcpe from mojang build_leveldb = None if (not os.path.exists(mcpeso_dir)) or (not 'libleveldb.so' in os.listdir(mcpeso_dir)): build_leveldb = True elif os.path.exists(os.path.join(mcpeso_dir, 'libleveldb.so')): a = raw_input("Mojang's leveldb is already built. Rebuild [y/N] ?") if a and a in 'yY': build_leveldb = True else: build_leveldb = False else: not_exists = [os.path.basename(a) for a in (os.path.join(mcpeso_dir, 'libleveldb.a'), os.path.join(mcpeso_dir, 'libleveldb.so')) if not os.path.exists(a)] print "The file %s is missing. Building MCEdit one may not work." % not_exists[0] a = raw_input("Rebuild Mojang's leveldb-mcpe [y/N] ?") if a and a in 'yY': build_leveldb = True if build_leveldb is None: # Shall not happen... print "Impossible to determine if Mojang's leveldb-mcpe is already built or not..." a = raw_input('Do you want to (re)build it [y/N] ?') if a and a in 'yY': build_leveldb = True extract = False if build_leveldb: if os.path.exists('leveldb-mcpe') and os.listdir('leveldb-mcpe') != []: a = raw_input("Mojang's leveldb-mcpe source directory already exists. Replace it (reextract) [y/N] ?") if not a or a not in 'yY': extract = False else: extract = True if extract: os.system('rm -R leveldb-mcpe') if not os.path.exists('leveldb-mcpe-master.zip'): # Retrieve Mojang resource linked in MCEdit sources. I know, freaking command line :p os.system("""wget -O leveldb-mcpe-master.zip $(wget -S -O - https://github.com/Mojang/leveldb-mcpe/tree/$(wget -S -O - https://github.com/Khroki/MCEdit-Unified/tree/master/leveldb_mcpe | egrep -o '@ <a href="/Mojang/leveldb-mcpe/tree/([0-9A-Za-z]*)"' | egrep -o '/[0-9A-Za-z]*"' | egrep -o '[0-9A-Za-z]*') | egrep '\.zip' | sed 's/<a href="\/Mojang\/leveldb-mcpe\/archive/https:\/\/codeload.github.com\/Mojang\/leveldb-mcpe\/zip/' | sed 's/.zip"//'| sed 's/ //')""") print "Extracting Mojang's leveldb-mcpe..." os.system('unzip -q leveldb-mcpe-master.zip') os.system("mv $(ls -d1 */ | egrep 'leveldb-mcpe-') leveldb-mcpe") os.chdir('leveldb-mcpe') if not os.path.exists('../zlib.zip'): os.system('wget -O ../zlib.zip http://zlib.net/zlib128.zip') os.system('unzip -q ../zlib.zip') os.system("mv $(ls -d1 */ | egrep 'zlib-') zlib") os.chdir('..') if build_leveldb: os.chdir('leveldb-mcpe') print "Building Mojang's leveldb-mcpe..." data = open('Makefile').read() data = data.replace('LIBS += $(PLATFORM_LIBS) -lz', 'LIBS += $(PLATFORM_LIBS)') open('Makefile', 'w').write(data) os.system('make') os.chdir(curdir) print 'Done.' else: print "Skipping Mojang's leveldb-mcpe build." if not os.path.exists(os.path.join(mcpeso_dir, 'libleveldb.so.1.18')): print 'Copying library to %s.' % mcpeso_dir if not os.path.exists(mcpeso_dir): os.makedirs(mcpeso_dir) os.system('cp ./leveldb-mcpe/libleveldb.so.1.18 %s' % mcpeso_dir) os.system('ln -s %s/libleveldb.so.1.18 %s/libleveldb.so.1' % (mcpeso_dir, mcpeso_dir)) os.system('ln -s %s/libleveldb.so.1.18 %s/libleveldb.so' % (mcpeso_dir, mcpeso_dir)) print 'Done.' print 'Building leveldb_mcpe...' # #1# This form compiles dynamic shared library # include_dirs = [boosRoot, './leveldb-mcpe/include', '.'] # library_dirs = [boostRoot, boostRoot + '/stage/lib', '/usr/local/lib', '.', './leveldb-mcpe'] # libraries = ['boost_python', 'leveldb'] # define_macros = [("LINUX", None),("_DEBUG", None),("_LINUX", None),("LEVELDB_PLATFORM_POSIX", None)] # extra_compile_args = ['-std=c++11'] + extra_compile_args # runtime_library_dirs = ['.', './leveldb-mcpe'] # Need to copy libboost_python.so.1.55.0 in the current directory and link it # os.system('cp %s/stage/lib/libboost_python.so.1.55.0 .|ln -s ' # 'libboost_python.so.1.55.0 libboost_python.so' % boostRoot) # 2# Static library build: need a boost python libs built with cxxflags"-fPIC" and linkflags="-fPIC" include_dirs = [boostRoot, './leveldb-mcpe/include', '.'] library_dirs = [boostRoot, boostRoot + '/stage/lib', '/usr/local/lib', '.', mcpeso_dir] libraries = ['boost_python', 'leveldb'] define_macros = [("LINUX", None), ("_LINUX", None), ("LEVELDB_PLATFORM_POSIX", None), ('OS_LINUX', None)] extra_compile_args = ['-std=c++11', '-fPIC'] + extra_compile_args runtime_library_dirs = [mcpeso_dir] extra_link_args += ['-v'] files = ["leveldb_mcpe.cpp"] setup(name="leveldb_python_wrapper", ext_modules=[ Extension( "leveldb_mcpe", files, library_dirs=library_dirs, libraries=libraries, include_dirs=include_dirs, depends=[], define_macros=define_macros, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, runtime_library_dirs=runtime_library_dirs) ] ) # Need to copy leveldb_mcpe.so in the current directory if sys.platform == 'linux2': os.system('cp $(ls -R build/*/leveldb_mcpe.so) %s' % destpath) # Link the library and run the test os.system('ln -s %s/leveldb_mcpe.so leveldb_mcpe.so'%destpath) os.system('python test.py') # Delete the link os.system('rm leveldb_mcpe.so')
11,573
43.860465
478
py
MCEdit-Unified
MCEdit-Unified-master/leveldb_mcpe/setupnx.py
#!/usr/bin/python2 # -*- coding: utf-8 # # setupnx.py # # Build leveldb-mcpe for MCEdit-unified. # # D.C.-G. (LaChal) 2015 # from setuptools import setup from distutils.extension import Extension import os import sys import platform extra_compile_args = ["-DDLLX="] extra_link_args = [] define_macros = [] runtime_library_dirs = [] library_dirs = [] libraries = [] include_dirs = [] bin_deps = ('gcc', 'g++', 'tar', 'unzip') if sys.platform != "linux2": print "This script can't run on other platforms than Linux ones..." sys.exit(1) if sys.argv[-1] == 'setupnx.py': print 'No command specified. Aborting.' print 'Please, use `python setup.py build` to build Pocket Edition support for MCEdit.' sys.exit(1) print "Building Linux application 'leveldb_mcpe'..." # TODO: add checks, warnings and advice if something fails... (<< On the way) # add a cleanup option # 'build_ext --inplace' is not wanted here. Let it be replaced with build if '--inplace' in sys.argv: sys.argv.remove('--inplace') if 'build_ext' in sys.argv: sys.argv.remove('build_ext') sys.argv.append('build') # Verify the binary and library dependencies are satisfied # Check here for gcc, g++, tar, unzip print 'Searching for the binaries needed %s...'%repr(bin_deps).replace("'", '') missing_bin = False for name in bin_deps: if os.system('which %s > /dev/null'%name): print '*** WARNING: %s not found.'%name missing_bin = True if missing_bin: a = raw_input('The binary dependencies are not satisfied. The build may fail.\nContinue [y/N]?') if a and a in 'yY': pass else: sys.exit() else: print 'All the needed binaries were found.' # Picked from another project to find the lib and adapted to the need import re ARCH = {'32bit': '32', '64bit': '64'}[platform.architecture()[0]] default_paths = ['/lib', '/lib32', '/lib64', '/usr/lib', '/usr/lib32', '/usr/lib64', '/usr/local/lib', os.path.expanduser('~/.local/lib')] # Gather the libraries paths. def getLibPaths(file_name): paths = [] lines = [a.strip() for a in open(file_name).readlines()] for i, line in enumerate(lines): if not line.startswith('#') and line.strip(): if line.startswith('include'): line = line.split(' ', 1)[1] if '*' in line: pat = r"%s"%line.split(os.path.sep)[-1].replace('.', '\.').replace('*', '.*') d = os.path.split(line)[0] for n in os.listdir(d): r = re.findall(pat, n) if r: paths += [a for a in getLibPaths(os.path.join(d, n)) if a not in paths] else: paths += [a for a in getLibPaths(line) if not a in paths] elif not line in paths: paths.append(line) return paths def findLib(lib_name, input_file='/etc/ld.so.conf'): paths = default_paths + getLibPaths(input_file) arch_paths = [] other_paths = [] while paths: path = paths.pop(0) if ARCH in path: arch_paths.append(path) elif path.endswith('/lib'): arch_paths.insert(-1, path) else: other_paths.append(path) paths = arch_paths + other_paths found = False name = lib_name hash_list = name.split('.') hash_list.reverse() idx = hash_list.index('so') i = 0 while i <= idx and not found: for path in paths: if os.path.exists(path): for path, dirnames, filenames in os.walk(path): if name in filenames: found = os.path.join(path, name) break if found: break i += 1 name = name.rsplit('.', 1)[0] if found: if os.path.split(found)[0] in arch_paths: r = True else: r = False return found, r else: return None, None print 'Searching for zlib library (ideal version is 1.2.8)...' zlib = findLib('libz.so.1.2.8') if zlib == (None, None): zlib = None print '*** WARNING: zlib not found. It is recommended you stop now and install' print ' it (version 1.2.8) before you retry.' print ' If you decide to continue, the support for Pocket Edition' print ' may not work properly.' a = raw_input('Continue [y/N]? ') if a and a in 'yY': pass else: sys.exit(1) else: if zlib[1] == False: print '*** WARNING: zlib has been found on your system, but not for the' print ' current architecture. You apparently run on a %s, and the found zlib is %s'%(ARCH, found[0]) print ' Building the Pocket Edition support may fail. If not,' print ' the support may not work.' print ' You can continue, but it is recommended 1.2.8 for your' print ' architecture.' a = raw_input('Continue [y/N]? ') if a and a in 'yY': zlib = zlib[0] else: sys.exit(1) else: zlib = zlib[0] print 'Found %s.'%zlib if os.path.split(zlib)[-1] != 'libz.so.1.2.8': print 'But the exact version could not be determined.' print 'If the build fails or the support does not work, install the version' print '1.2.8 and retry.' # Unpack and build dependencies: boost and mojang's leveldb-mcpe # Need make, g++, tar, unzip, Python 2.7 header files # boost will be installed there to avoid elevation problems curdir = os.getcwd() destpath = '../pymclevel' # Check if leveldb_mcpe is already built if (not os.system('ls -R build/*/leveldb_mcpe.so 1> /dev/null 2>&1')) or os.path.exists(os.path.join(destpath, 'leveldb_mcpe.so')): a =raw_input('The library is already present. Do you want to recompile [y/N]?') if a and a in 'yY': if os.path.exists('build'): os.system('rm -R build') if os.path.exists(os.path.join(destpath, 'leveldb_mcpe.so')): os.system('rm %s'%os.path.join(destpath, 'leveldb_mcpe.so')) else: print 'Exiting.' sys.exit(0) # Check if the user library directory exists user_libdir = os.path.expanduser('~/.local/lib') if not os.path.exists(user_libdir): print 'Creating needed library folder: %s' % user_libdir os.makedirs(user_libdir) print 'Done' # Set the definitive Mojang's leveldb-mcpe lib directory to the user's one mcpeso_dir = os.path.join(user_libdir, 'leveldb-mcpe') # Check and install Boost boost_version = '1.58.0' boostRoot = os.path.expanduser('~/.local/lib/boost_%s_mcpe'%boost_version.replace('.', '_')) install_boost = None build_boost_python = None if not os.path.exists(boostRoot): install_boost = True else: a = raw_input('Boost found in %s.\nDo you want to reinstall it [y/N]?' % boostRoot) if a and a in 'yY': install_boost = True else: install_boost = False if not os.path.exists(os.path.join(boostRoot, 'stage', 'lib', 'libboost_python.a')): build_boost_python = True else: a = raw_input('Boost Python wrapper found in %s.\nDo you want to rebuild it [y/N]?' % os.path.join(boostRoot, 'stage', 'lib')) if a and a in 'yY': build_boost_python = True else: build_boost_python = False if install_boost is None: # Shall not happen... print 'Impossible to determine if Boost %s is installed in your personnal library folder.'%boost_version a = raw_input('Do you want to (re)install it [y/N] ?') if a and a in 'yY': install_boost = True if build_boost_python is None: # Shall not happen... print 'Impossible to determine if Boost Python wrapper is installed in your personnal library folder.' a = raw_input('Do you want to (re)install it [y/N] ?') if a and a in 'yY': build_boost_python = True if install_boost: print "Dowloading Boost %s from SourceForge..."%boost_version os.system('wget http://freefr.dl.sourceforge.net/project/boost/boost/%s/boost_%s.tar.bz2'%(boost_version, boost_version.replace('.', '_'))) print "Extracting boost..." os.system('tar --bzip2 -xf boost_%s.tar.bz2'%boost_version.replace('.', '_')) os.system('mv boost_%s %s' % (boost_version.replace('.', '_'), boostRoot)) os.chdir(boostRoot) print "Installing boost..." os.system('sh ./bootstrap.sh --prefix=%s' % boostRoot) os.chdir(curdir) print 'Done.' if build_boost_python: print "Building boost_python..." os.chdir(boostRoot) os.system('./b2 --with-python --prefix=%s --build-dir=%s -a link=static cxxflags="-fPIC" linkflags="-fPIC"' % ( boostRoot, boostRoot)) os.chdir(curdir) print 'Done.' # Unpack and build leveldb-mcpe from mojang build_leveldb = None if (not os.path.exists(mcpeso_dir)) or (not 'libleveldb.so' in os.listdir(mcpeso_dir)): build_leveldb = True elif os.path.exists(os.path.join(mcpeso_dir, 'libleveldb.so')): a = raw_input("Mojang's leveldb is already built. Rebuild [y/N] ?") if a and a in 'yY': build_leveldb = True else: build_leveldb = False else: not_exists = [os.path.basename(a) for a in (os.path.join(mcpeso_dir, 'libleveldb.a'), os.path.join(mcpeso_dir, 'libleveldb.so')) if not os.path.exists(a)] print "The file %s is missing. Building MCEdit one may not work." % not_exists[0] a = raw_input("Rebuild Mojang's leveldb-mcpe [y/N] ?") if a and a in 'yY': build_leveldb = True if build_leveldb is None: # Shall not happen... print "Impossible to determine if Mojang's leveldb-mcpe is already built or not..." a = raw_input('Do you want to (re)build it [y/N] ?') if a and a in 'yY': build_leveldb = True extract = False if build_leveldb: if os.path.exists('leveldb-mcpe') and os.listdir('leveldb-mcpe') != []: a = raw_input("Mojang's leveldb-mcpe source directory already exists. Replace it (reextract) [y/N] ?") if not a or a not in 'yY': extract = False else: extract = True if extract: os.system('rm -R leveldb-mcpe') if not os.path.exists('leveldb-mcpe-master.zip'): # Retrieve Mojang resource linked in MCEdit sources. I know, freaking command line :p # os.system("""wget -O leveldb-mcpe-master.zip $(wget -S -O - https://github.com/Mojang/leveldb-mcpe/tree/$(wget -S -O - https://github.com/Khroki/MCEdit-Unified/tree/master/leveldb_mcpe | egrep -o '@ <a href="/Mojang/leveldb-mcpe/tree/([0-9A-Za-z]*)"' | egrep -o '/[0-9A-Za-z]*"' | egrep -o '[0-9A-Za-z]*') | egrep '\.zip' | sed 's/<a href="\/Mojang\/leveldb-mcpe\/archive/https:\/\/codeload.github.com\/Mojang\/leveldb-mcpe\/zip/' | sed 's/.zip"//'| sed 's/ //')""") # Mojang's repo reference has been removed from MCEdit repo... # Using hard coded reference now. os.system("""wget -O leveldb-mcpe-master.zip https://codeload.github.com/Mojang/leveldb-mcpe/zip/a056ea7c18dfd7b806d6d693726ce79d75543904""") print "Extracting Mojang's leveldb-mcpe..." os.system('unzip -q leveldb-mcpe-master.zip') os.system("mv $(ls -d1 */ | egrep 'leveldb-mcpe-') leveldb-mcpe") os.chdir('leveldb-mcpe') if not os.path.exists('../zlib.tar.gz'): os.system('wget -O ../zlib.tar.gz http://zlib.net/fossils/zlib-1.2.8.tar.gz') os.system('tar xvf ../zlib.tar.gz') os.system("mv $(ls -d1 */ | egrep 'zlib-') zlib") os.chdir('..') if build_leveldb: os.chdir('leveldb-mcpe') print "Building Mojang's leveldb-mcpe..." data = open('Makefile').read() if zlib: replacer = 'LIBS += $(PLATFORM_LIBS) %s'%zlib else: replacer = 'LIBS += $(PLATFORM_LIBS)' data = data.replace('LIBS += $(PLATFORM_LIBS) -lz', replacer) open('Makefile', 'w').write(data) os.system('make') os.chdir(curdir) print 'Done.' else: print "Skipping Mojang's leveldb-mcpe build." if not os.path.exists(os.path.join(mcpeso_dir, 'libleveldb.so.1.18')): print 'Copying library to %s.' % mcpeso_dir if not os.path.exists(mcpeso_dir): os.makedirs(mcpeso_dir) os.system('cp ./leveldb-mcpe/libleveldb.so.1.18 %s' % destpath) os.system('ln -s %s/libleveldb.so.1.18 %s/libleveldb.so.1.18' % (destpath, mcpeso_dir)) os.system('ln -s %s/libleveldb.so.1.18 %s/libleveldb.so.1' % (destpath, mcpeso_dir)) os.system('ln -s %s/libleveldb.so.1.18 %s/libleveldb.so' % (destpath, mcpeso_dir)) print 'Done.' print 'Building leveldb_mcpe...' # #1# This form compiles dynamic shared library # include_dirs = [boosRoot, './leveldb-mcpe/include', '.'] # library_dirs = [boostRoot, boostRoot + '/stage/lib', '/usr/local/lib', '.', './leveldb-mcpe'] # libraries = ['boost_python', 'leveldb'] # define_macros = [("LINUX", None),("_DEBUG", None),("_LINUX", None),("LEVELDB_PLATFORM_POSIX", None)] # extra_compile_args = ['-std=c++11'] + extra_compile_args # runtime_library_dirs = ['.', './leveldb-mcpe'] # Need to copy libboost_python.so.1.55.0 in the current directory and link it # os.system('cp %s/stage/lib/libboost_python.so.1.55.0 .|ln -s ' # 'libboost_python.so.1.55.0 libboost_python.so' % boostRoot) # 2# Static library build: need a boost python libs built with cxxflags"-fPIC" and linkflags="-fPIC" include_dirs = [boostRoot, './leveldb-mcpe/include', '.'] library_dirs = [boostRoot, boostRoot + '/stage/lib', '/usr/local/lib', '.', mcpeso_dir] libraries = ['boost_python', 'leveldb'] define_macros = [("LINUX", None), ("_LINUX", None), ("LEVELDB_PLATFORM_POSIX", None), ('OS_LINUX', None)] extra_compile_args = ['-std=c++11', '-fPIC'] + extra_compile_args runtime_library_dirs = [mcpeso_dir] extra_link_args += ['-v'] files = ["leveldb_mcpe.cpp"] setup(name="leveldb_python_wrapper", ext_modules=[ Extension( "leveldb_mcpe", files, library_dirs=library_dirs, libraries=libraries, include_dirs=include_dirs, depends=[], define_macros=define_macros, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args, runtime_library_dirs=runtime_library_dirs) ] ) # Need to copy leveldb_mcpe.so in the current directory os.system('cp $(ls -R build/*/leveldb_mcpe.so) %s' % destpath) # Link the library and run the test os.system('ln -s %s/leveldb_mcpe.so leveldb_mcpe.so'%destpath) os.system('python test.py') # Delete the link os.system('rm leveldb_mcpe.so')
14,577
37.46438
476
py
msutils
msutils-master/setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 SKA South Africa # # # 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/>. import subprocess import os from setuptools import setup pkg='MSUtils' build_root=os.path.dirname(__file__) def readme(): with open(os.path.join(build_root, 'README.md')) as f: return f.read() def requirements(): with open(os.path.join(build_root, 'requirements.txt')) as f: return [pname.strip() for pname in f.readlines()] def src_pkg_dirs(pkg_name): mbdir = os.path.join(build_root, pkg_name) # Ignore pkg_dirs = [] l = len(mbdir) + len(os.sep) exclude = ['docs', '.git', '.svn', 'CMakeFiles'] for root, dirs, files in os.walk(mbdir, topdown=True): # Prune out everything we're not interested in # from os.walk's next yield. dirs[:] = [d for d in dirs if d not in exclude] for d in dirs: # Take everything after that ('src...') and # append a '/*.*' to it pkg_dirs.append(os.path.join(root[l:], d, '*.*')) return pkg_dirs setup(name='msutils', version="1.2.0", description='Tools for playing with Measurement sets.', long_description=readme(), url='https://github.com/SpheMakh/msutils', classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Developers", # "License :: GNU GPL v2", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Scientific/Engineering :: Astronomy"], author='Sphesihle Makhathini', author_email='[email protected]', license='GNU GPL v2', packages=[pkg], install_requires=requirements(), package_data={pkg: src_pkg_dirs(pkg)}, include_package_data=True, python_requires='>=3.6' )
2,494
32.266667
71
py
msutils
msutils-master/MSUtils/msutils.py
from pyrap.tables import table import pyrap.tables import pyrap.measures import numpy import traceback from pyrap.tables import maketabdesc from pyrap.tables import makearrcoldesc from pyrap.tables import makescacoldesc from distutils import spawn import sys import subprocess import math import json import codecs import os dm = pyrap.measures.measures() STOKES_TYPES = { 0 : "Undefined", 1 : "I", 2 : "Q", 3 : "U", 4 : "V", 5 : "RR", 6 : "RL", 7 : "LR", 8 : "LL", 9 : "XX", 10 : "XY", 11 : "YX", 12 : "YY", 13 : "RX", 14 : "RY", 15 : "LX", 16 : "LY", 17 : "XR", 18 : "XL", 19 : "YR", 20 : "YL", 21 : "PP", 22 : "PQ", 23 : "QP", 24 : "QQ", 25 : "RCircular", 26 : "LCircular", 27 : "Linear", 28 : "Ptotal", 29 : "Plinear", 30 : "PFtotal", 31 : "PFlinear", 32 : "Pangle", } def summary(msname, outfile=None, display=True): tab = pyrap.tables.table(msname) info = { "FIELD" : {}, "SPW" : {}, "ANT" : {}, "MAXBL" : {}, "SCAN" : {}, "EXPOSURE" : {}, "NROW" : tab.nrows(), "CORR" : {}, } tabs = { 'FIELD' : pyrap.tables.table(msname+'::FIELD'), 'SPW' : pyrap.tables.table(msname+'::SPECTRAL_WINDOW'), 'ANT' : pyrap.tables.table(msname+'::ANTENNA'), } state_tab = pyrap.tables.table(msname+'::STATE') info['FIELD']['INTENTS'] = state_tab.getcol('OBS_MODE') state_tab.close() fields = numpy.unique(tab.getcol("FIELD_ID")) info["FIELD"]["FIELD_ID"] = list(map(int, fields)) nfields = len(fields) nant = tabs['ANT'].nrows() info['EXPOSURE'] = tab.getcell("EXPOSURE", 0) info['FIELD']['STATE_ID'] = [None]*nfields info['FIELD']['PERIOD'] = [None]*nfields for i, fid in enumerate(fields): ftab = tab.query('FIELD_ID=={0:d}'.format(fid)) state_id = ftab.getcol('STATE_ID')[0] info['FIELD']['STATE_ID'][i] = int(state_id) scans = {} total_length = 0 for scan in set(ftab.getcol('SCAN_NUMBER')): stab = ftab.query('SCAN_NUMBER=={0:d}'.format(scan)) length = (stab.getcol('TIME').max() - stab.getcol('TIME').min()) stab.close() scans[str(scan)] = length total_length += length info['SCAN'][str(fid)] = scans info['FIELD']['PERIOD'][i] = total_length ftab.close() for key, _tab in list(tabs.items()): if key == 'SPW': colnames = 'CHAN_FREQ MEAS_FREQ_REF REF_FREQUENCY TOTAL_BANDWIDTH NAME NUM_CHAN IF_CONV_CHAIN NET_SIDEBAND FREQ_GROUP_NAME'.split() else: colnames = _tab.colnames() for name in colnames: try: info[key][name] = _tab.getcol(name).tolist() except AttributeError: info[key][name] = _tab.getcol(name) _tab.close() # add correlation information tabcorr = pyrap.tables.table(msname+'::POLARIZATION') corr_type = tabcorr.getcol("CORR_TYPE")[0] info["CORR"]["NUM_CORR"] = int(tabcorr.getcol("NUM_CORR")[0]) info["NCOR"] = int(info["CORR"]["NUM_CORR"]) corrs = [] for ct in corr_type: corrs.append( STOKES_TYPES[ct] ) info["CORR"]["CORR_TYPE"] = corrs tabcorr.close() # get maximum baseline uv = tab.getcol("UVW")[:,:2] mb = numpy.sqrt((uv**2).sum(1)).max() info['MAXBL'] = mb tab.close() if display: print(info) if outfile: with codecs.open(outfile, 'w', 'utf8') as stdw: stdw.write(json.dumps(info, ensure_ascii=False)) return info def addcol(msname, colname=None, shape=None, data_desc_type='array', valuetype=None, init_with=None, coldesc=None, coldmi=None, clone='DATA', rowchunk=None, **kw): """ Add column to MS msanme : MS to add colmn to colname : column name shape : shape valuetype : data type data_desc_type : 'scalar' for scalar elements and array for 'array' elements init_with : value to initialise the column with """ tab = table(msname,readonly=False) if colname in tab.colnames(): print('Column already exists') return 'exists' print(('Attempting to add %s column to %s'%(colname,msname))) valuetype = valuetype or 'complex' if coldesc: data_desc = coldesc shape = coldesc['shape'] elif shape: data_desc = maketabdesc(makearrcoldesc(colname, init_with, shape=shape, valuetype=valuetype)) elif valuetype == 'scalar': data_desc = maketabdesc(makearrcoldesc(colname, init_with, valuetype=valuetype)) elif clone: element = tab.getcell(clone, 0) try: shape = element.shape data_desc = maketabdesc(makearrcoldesc(colname, element.flatten()[0], shape=shape, valuetype=valuetype)) except AttributeError: shape = [] data_desc = maketabdesc(makearrcoldesc(colname, element, valuetype=valuetype)) colinfo = [data_desc, coldmi] if coldmi else [data_desc] tab.addcols(*colinfo) print('Column added successfuly.') if init_with is None: tab.close() return 'added' else: spwids = set(tab.getcol('DATA_DESC_ID')) for spw in spwids: print(('Initialising {0:s} column with {1}. DDID is {2:d}'.format(colname, init_with, spw))) tab_spw = tab.query('DATA_DESC_ID=={0:d}'.format(spw)) nrows = tab_spw.nrows() rowchunk = rowchunk or nrows/10 dshape = [0] + [a for a in shape] for row0 in range(0,nrows,rowchunk): nr = min(rowchunk,nrows-row0) dshape[0] = nr print(("Wrtiting to column %s (rows %d to %d)"%(colname, row0, row0+nr-1))) tab_spw.putcol(colname,numpy.ones(dshape,dtype=type(init_with))*init_with,row0,nr) tab_spw.close() tab.close() return 'added' def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, subtract=False): """ Add col1 to col2, or sum columns in 'cols' list. If subtract, subtract col2 from col1 """ tab = table(msname, readonly=False) if outcol not in tab.colnames(): print(('outcol {0:s} does not exist, will add it first.'.format(outcol))) addcol(msname, outcol, clone=col1 or cols[0]) spws = set(tab.getcol('DATA_DESC_ID')) for spw in spws: tab_spw = tab.query('DATA_DESC_ID=={0:d}'.format(spw)) nrows = tab_spw.nrows() rowchunk = nrows//10 if nrows > 10000 else nrows for row0 in range(0, nrows, rowchunk): nr = min(rowchunk, nrows-row0) print(("Wrtiting to column %s (rows %d to %d)"%(outcol, row0, row0+nr-1))) if subtract: data = tab_spw.getcol(col1, row0, nr) - tab_spw.getcol(col2, row0, nr) else: cols = cols or [col1, col2] data = 0 for col in cols: data += tab.getcol(col, row0, nr) tab_spw.putcol(outcol, data, row0, nr) tab_spw.close() tab.close() def copycol(msname, fromcol, tocol): """ Copy data from one column to another """ tab = table(msname, readonly=False) if tocol not in tab.colnames(): addcol(msname, tocol, clone=fromcol) spws = set(tab.getcol('DATA_DESC_ID')) for spw in spws: tab_spw = tab.query('DATA_DESC_ID=={0:d}'.format(spw)) nrows = tab_spw.nrows() rowchunk = nrows//10 if nrows > 5000 else nrows for row0 in range(0, nrows, rowchunk): nr = min(rowchunk, nrows-row0) data = tab_spw.getcol(fromcol, row0, nr) tab_spw.putcol(tocol, data, row0, nr) tab_spw.close() tab.close() def compute_vis_noise(msname, sefd, spw_id=0): """Computes nominal per-visibility noise""" tab = table(msname) spwtab = table(msname + "::SPECTRAL_WINDOW") freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0] wavelength = 300e+6/freq0 bw = spwtab.getcol("CHAN_WIDTH")[spw_id, 0] dt = tab.getcol("EXPOSURE", 0, 1)[0] dtf = (tab.getcol("TIME", tab.nrows()-1, 1)-tab.getcol("TIME", 0, 1))[0] # close tables properly, else the calls below will hang waiting for a lock... tab.close() spwtab.close() print(("%s freq %.2f MHz (lambda=%.2fm), bandwidth %.2g kHz, %.2fs integrations, %.2fh synthesis"%(msname, freq0*1e-6, wavelength, bw*1e-3, dt, dtf/3600))) noise = sefd/math.sqrt(abs(2*bw*dt)) print(("SEFD of %.2f Jy gives per-visibility noise of %.2f mJy"%(sefd, noise*1000))) return noise def verify_antpos (msname, fix=False, hemisphere=None): """Verifies antenna Y positions in MS. If Y coordinate convention is wrong, either fixes the positions (fix=True) or raises an error. hemisphere=-1 makes it assume that the observatory is in the Western hemisphere, hemisphere=1 in the Eastern, or else tries to find observatory name using MS and pyrap.measure.""" if not hemisphere: obs = table(msname+"::OBSERVATION").getcol("TELESCOPE_NAME")[0] print(("observatory is %s"%obs)) try: hemisphere = 1 if dm.observatory(obs)['m0']['value'] > 0 else -1 except: traceback.print_exc(); print(("WARNING:: %s is unknown, or pyrap.measures is missing. Will not verify antenna positions."%obs)) return print(("antenna Y positions should be of sign %+d"%hemisphere)) anttab = table(msname+"::ANTENNA", readonly=False) pos = anttab.getcol("POSITION") wrong = pos[:,1]<0 if hemisphere>0 else pos[:,1]>0 nw = sum(wrong) if nw: if not fix: os.abort("%s/ANTENNA has $nw incorrect Y antenna positions. Check your coordinate conversions (from UVFITS?), or run verify_antpos[fix=True]"%msname) pos[wrong,1] *= -1; anttab.putcol("POSITION", pos) print(("WARNING:%s/ANTENNA: %s incorrect antenna positions were adjusted (Y sign flipped)"%(msname, nw))) else: print(("%s/ANTENNA: all antenna positions appear to have correct Y sign"%msname)) def prep(msname, verify=False): """Prepares MS for use with MeqTrees: adds imaging columns, adds BITFLAG columns, copies current flags to 'legacy' flagset """ if verify: verify_antpos(msname, fix=verify); print("Adding imaging columns") pyrap.tables.addImagingColumns(msname) # check if addbitflagcol exists if spawn.find_executable("addbitflagcol"): print(("Adding bitflag column to %s"%msname)) subprocess.check_call(['addbitflagcol', msname], stderr=subprocess.PIPE if not isinstance(sys.stderr,file) else sys.stderr, # noqa: F821 stdout=subprocess.PIPE if not isinstance(sys.stdout,file) else sys.stdout) # noqa: F821 if spawn.find_executable("flag-ms.py"): print("Copying FLAG to bitflag 'legacy'") subprocess.check_call(['flag-ms.py', '-Y', '+L', '-f', 'legacy', '-c', msname], stderr=subprocess.PIPE if not isinstance(sys.stderr,file) else sys.stderr, # noqa: F821 stdout=subprocess.PIPE if not isinstance(sys.stdout,file) else sys.stdout) # noqa: F821 print("Flagging INFs/NaNs in data") subprocess.Popen(['flag-ms.py', '--nan', '-f', 'legacy', '--data-column', 'DATA', '-x', msname], stderr=subprocess.PIPE if not isinstance(sys.stderr,file) else sys.stderr, # noqa: F821 stdout=subprocess.PIPE if not isinstance(sys.stdout,file) else sys.stdout) # noqa: F821 def addnoise(msname, column='MODEL_DATA', noise=0, sefd=551, rowchunk=None, addToCol=None, spw_id=None): """ Add Gaussian noise to MS, given a stdandard deviation (noise). This noise can be also be calculated given SEFD value """ tab = table(msname, readonly=False) multi_chan_noise = False if hasattr(noise, '__iter__'): multi_chan_noise = True elif hasattr(sefd, '__iter__'): multi_chan_noise = True else: noise = noise or compute_vis_noise(msname, sefd=sefd, spw_id=spw_id or 0) spws = set(tab.getcol('DATA_DESC_ID')) for spw in spws: tab_spw = tab.query('DATA_DESC_ID=={0:d}'.format(spw)) nrows = tab_spw.nrows() nchan,ncor = tab_spw.getcell('DATA', 0).shape rowchunk = rowchunk or nrows/10 for row0 in range(0, nrows, rowchunk): nr = min(rowchunk, nrows-row0) data = numpy.random.randn(nr, nchan, ncor) + 1j*numpy.random.randn(nr, nchan, ncor) if multi_chan_noise: noise = noise[numpy.newaxis,:,numpy.newaxis] data *= noise if addToCol: data += tab_spw.getcol(addToCol, row0, nr) print(("%s + noise --> %s (rows %d to %d)"%(addToCol, column, row0, row0+nr-1))) else: print(("Adding noise to column %s (rows %d to %d)"%(column, row0, row0+nr-1))) tab_spw.putcol(column, data, row0, nr) tab_spw.close() tab.close()
13,798
32.492718
161
py
msutils
msutils-master/MSUtils/imp_plotter.py
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np from pyrap.tables import table def plot_bandpass_table(gain_table, plt_scale=6, plt_dpi=600, plot_file=None): #Reads in the gain table; makes plots of gain amplitude/phase with #time/frequency for all the antennas. #Read in the table plot_file = plot_file or gain_table+'.png' G_tab = table(gain_table) print(('Reading gain table:', gain_table, '\n')) G_tab_names = table(gain_table+"::ANTENNA") ant_names = G_tab_names.getcol("NAME") print(("Antennas present in the table:", ant_names)) #Get number of antennas (needed for plotting) N_ants = len(ant_names) print(('Number of Antennas to plot:', N_ants)) #Read in the Frequency information G_tab_freq = table(gain_table+"::SPECTRAL_WINDOW") FRQ = G_tab_freq.getcol('CHAN_FREQ') FRQ_GHZ = np.round(FRQ[0,:]/10**9,4) #Read in the flags flags = G_tab.getcol("FLAG") #Read in the solutions Gsols = G_tab.getcol("CPARAM") nchans = Gsols.shape[1] nsols = Gsols.shape[0]//N_ants npol = Gsols.shape[2] #Read in the error. Additions of the parameter errors in a later release. Gsols_err = G_tab.getcol("PARAMERR") #Read in the timestamps. # Gsols_time = G_tab.getcol("TIME") #Prepare for plotting; store gain amp and phases. Gsols_HH = Gsols[:,:,0] Gsols_VV = Gsols[:,:,1] # print "Shape of solutions:", np.shape(Gsols_HH), np.shape(Gsols_VV) Gsols_HH_flag = np.ma.masked_array(Gsols_HH, mask=flags[:,:,0]) Gsols_VV_flag = np.ma.masked_array(Gsols_VV, mask=flags[:,:,1]) Gsols_HH_amp = abs(Gsols_HH_flag) Gsols_VV_amp = abs(Gsols_VV_flag) Gsols_HH_ph = (180.0/np.pi)*np.arctan2(Gsols_HH_flag.imag,Gsols_HH_flag.real) #Because np.angle does not respect masked arrays. Gsols_VV_ph = (180.0/np.pi)*np.arctan2(Gsols_VV_flag.imag,Gsols_VV_flag.real) # Gsols_HH_ph = np.angle(Gsols_HH_flag,deg=True) # Gsols_VV_ph = np.angle(Gsols_VV_flag,deg=True) #Plotting #Plot in a more or less square grid. nplts = int(np.sqrt(N_ants))+1 #(if non zero remainder, add one) #Set matplotlib options matplotlib.rcParams['lines.markersize'] = 4.0 matplotlib.rcParams['xtick.major.size'] = 5.0 matplotlib.rcParams['ytick.major.size'] = 5.0 matplotlib.rcParams['ytick.direction'] = 'out' matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['font.size'] = 15.0 matplotlib.rcParams['axes.linewidth'] = 3.0 matplotlib.rcParams['legend.framealpha'] = 0.5 matplotlib.rcParams['font.style'] = 'italic' # matplotlib.rcParams[] print("Starting plotting process") #plt_dpi=800 f, axarr = plt.subplots(nplts, nplts, dpi=plt_dpi, figsize=(nplts*plt_scale,nplts*plt_scale)) f.text(0.5,0.94,"Bandpass Plot",ha='center',fontsize=40) f.text(0.5, 0.04, 'Frequency (GHz)', ha='center',fontsize=30) f.text(0.04, 0.5, 'Gain Amp', va='center', rotation='vertical',fontsize=30) print("Defining plots completed") #Plot amplitudes first globmax = np.round(np.max(np.maximum(Gsols_VV_amp, Gsols_HH_amp)),1) globmin = np.round(np.min(np.minimum(Gsols_VV_amp, Gsols_HH_amp)),1) for ant in range(N_ants): for sol in range(nsols): axarr[ant // nplts, ant % nplts].plot(FRQ_GHZ,Gsols_HH_amp[ant+N_ants*sol],color='#4169E1', marker = '.', label='CORR0') axarr[ant // nplts, ant % nplts].plot(FRQ_GHZ,Gsols_VV_amp[ant+N_ants*sol],color='#FF681F', marker = '.', label='CORR1') if sol==0: axarr[ant // nplts, ant % nplts].legend() axarr[ant // nplts, ant % nplts].set_title('Antenna '+str(ant_names[ant])) axarr[ant // nplts, ant % nplts].set_ylim(globmin-0.05,globmax+0.05) for i in range(nplts): for j in range(nplts): if ( ((i*nplts)+(j+1))> N_ants): axarr[i,j].set_visible(False) print("iterating finished...") plot_f = plot_file+"-bandpass-amp.png" f.savefig(plot_f) print("plotting finished") plt.close(f) print("cleaning up") f, axarr = plt.subplots(nplts, nplts, dpi=plt_dpi, figsize=(nplts*plt_scale,nplts*plt_scale)) f.text(0.5,0.94,"Bandpass Plot",ha='center',fontsize=40) f.text(0.5, 0.04, 'Frequency(GHz)', ha='center',fontsize=30) f.text(0.04, 0.5, 'Gain Phase', va='center', rotation='vertical',fontsize=30) #Plot phases now globmaxph = np.round(np.max(np.maximum(Gsols_VV_ph, Gsols_HH_ph)),1) globminph = np.round(np.min(np.minimum(Gsols_VV_ph, Gsols_HH_ph)),1) for ant in range(N_ants): for sol in range(nsols): axarr[ant // nplts, ant % nplts].plot(FRQ_GHZ,Gsols_HH_ph[ant+N_ants*sol],color='#4169E1', marker = '.', label='CORR0') axarr[ant // nplts, ant % nplts].plot(FRQ_GHZ,Gsols_VV_ph[ant+N_ants*sol],color='#FF681F', marker = '.', label='CORR1') if sol==0: axarr[ant // nplts, ant % nplts].legend() axarr[ant // nplts, ant % nplts].set_title('Antenna '+str(ant_names[ant])) axarr[ant // nplts, ant % nplts].set_ylim(globminph-5.0,globmaxph+5.0) for i in range(nplts): for j in range(nplts): if ( ((i*nplts)+(j+1))> N_ants): axarr[i,j].set_visible(False) plot_f = plot_file+"-bandpass-phase.png" f.savefig(plot_f) plt.close(f) G_tab.close() G_tab_names.close() plt.clf() print("Plotting and cleaning over") def plot_gain_table(gain_table, plt_scale=6, plt_dpi=600, plot_file=None): #Reads in the gain table; makes plots of gain amplitude/phase with #time/frequency for all the antennas. #Read in the table plot_file = plot_file or gain_table+'.png' G_tab = table(gain_table) print(('Reading gain table:', gain_table, '\n')) G_tab_names = table(gain_table+"::ANTENNA") ant_names = G_tab_names.getcol("NAME") print(("Antennas present in the table:", ant_names)) #Get number of antennas (needed for plotting) Ant_n1 = G_tab.getcol("ANTENNA1") Ant_n2 = G_tab.getcol("ANTENNA2") Ant_list = list(set(np.append(Ant_n1,Ant_n2))) N_ants = len(ant_names) print(('Number of Antennas to plot:', N_ants)) #Read in the flags flags = G_tab.getcol("FLAG") #Read in the solutions Gsols = G_tab.getcol("CPARAM") nchans = Gsols.shape[1] nsols = Gsols.shape[0]//N_ants print(("Number of solution per antenna:", nsols)) npol = Gsols.shape[2] #Read in the error. Gsols_err = G_tab.getcol("PARAMERR") #Read in the timestamps Gsols_time = G_tab.getcol("TIME") #Prepare for plotting; store gain amp and phases. Gsols_HH = Gsols[:,:,0] Gsols_VV = Gsols[:,:,1] print(("Shape of solutions:", np.shape(Gsols_HH), np.shape(Gsols_VV))) Gsols_HH_flag = np.ma.masked_array(Gsols_HH, mask=flags[:,:,0]) Gsols_VV_flag = np.ma.masked_array(Gsols_VV, mask=flags[:,:,1]) Gsols_HH_amp = abs(Gsols_HH_flag) Gsols_VV_amp = abs(Gsols_VV_flag) Gsols_HH_ph = (180.0/np.pi)*np.arctan2(Gsols_HH_flag.imag,Gsols_HH_flag.real) #Because np.angle does not respect masked arrays Gsols_VV_ph = (180.0/np.pi)*np.arctan2(Gsols_VV_flag.imag,Gsols_VV_flag.real) #Gsols_HH_ph = np.angle(Gsols_HH_flag,deg=True) #Gsols_VV_ph = np.angle(Gsols_VV_flag,deg=True) #Plotting #Plot in a more or less square grid. nplts = int(np.sqrt(N_ants))+1 #(if non zero remainder, add one) #Set matplotlib options matplotlib.rcParams['lines.markersize'] = 15.0 matplotlib.rcParams['xtick.major.size'] = 5.0 matplotlib.rcParams['ytick.major.size'] = 5.0 matplotlib.rcParams['ytick.direction'] = 'out' matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['font.size'] = 15.0 matplotlib.rcParams['axes.linewidth'] = 3.0 matplotlib.rcParams['legend.framealpha'] = 0.5 # matplotlib.rcParams['font.family'] = 'sans-serif' # matplotlib.rcParams['font.sans-serif'] = 'Verdana' matplotlib.rcParams['font.style'] = 'italic' #Make a single plot for gain amplitude and phase, colourize different fields? obs_time = G_tab.getcol("TIME") #Scale to start time and scale to hours obs_time = obs_time-obs_time[0] obs_time = obs_time/3600.0 f, axarr = plt.subplots(nplts, nplts, dpi=plt_dpi, figsize=(nplts*plt_scale,nplts*plt_scale)) #Plot amplitudes first globmax = np.round(np.max(np.maximum(Gsols_VV_amp, Gsols_HH_amp)),1) globmin = np.round(np.min(np.minimum(Gsols_VV_amp, Gsols_HH_amp)),1) f.text(0.5,0.94,"Gain Amplitude Plot",ha='center',fontsize=40) f.text(0.5, 0.04, 'Time(Hours)', ha='center',fontsize=30) f.text(0.04, 0.5, 'Gain Amp', va='center', rotation='vertical',fontsize=30) for ant in range(N_ants): for sol in range(nsols): axarr[ant // nplts, ant % nplts].plot(obs_time[ant+N_ants*sol], Gsols_HH_amp[ant+N_ants*sol],color='#4169E1', marker = '.', label='CORR0') axarr[ant // nplts, ant % nplts].plot(obs_time[ant+N_ants*sol], Gsols_VV_amp[ant+N_ants*sol],color='#FF681F', marker = '.',label='CORR1') if sol==0: axarr[ant // nplts, ant % nplts].legend() axarr[ant // nplts, ant % nplts].set_title('Antenna '+str(ant_names[ant])) # axarr[ant // nplts, ant % nplts].set_xlabel('Time (Hours)') # axarr[ant // nplts, ant % nplts].set_ylabel('Gain Amplitude') # axarr[ant // nplts, ant % nplts].set_ylim(0,20) axarr[ant // nplts, ant % nplts].set_ylim(globmin-0.5,globmax+0.5) for i in range(nplts): for j in range(nplts): if ( ((i*nplts)+(j+1))> N_ants): axarr[i,j].set_visible(False) plot_f = plot_file+"-gain-amp.png" f.savefig(plot_f) plt.close(f) f, axarr = plt.subplots(nplts, nplts, dpi=plt_dpi, figsize=(nplts*plt_scale,nplts*plt_scale)) #Plot phases globmaxph = np.round(np.max(np.maximum(Gsols_VV_ph, Gsols_HH_ph)),1) globminph = np.round(np.min(np.minimum(Gsols_VV_ph, Gsols_HH_ph)),1) f.text(0.5,0.94,"Gain Phase Plot",ha='center',fontsize=40) f.text(0.5, 0.04, 'Time(Hours)', ha='center',fontsize=30) f.text(0.04, 0.5, 'Gain Phase(Degrees)', va='center', rotation='vertical',fontsize=30) for ant in range(N_ants): for sol in range(nsols): axarr[ant // nplts, ant % nplts].plot(obs_time[ant+N_ants*sol], Gsols_HH_ph[ant+N_ants*sol],color='#4169E1', marker = '.', label='CORR0') axarr[ant // nplts, ant % nplts].plot(obs_time[ant+N_ants*sol], Gsols_VV_ph[ant+N_ants*sol],color='#FF681F', marker = '.', label='CORR1') if sol==0: axarr[ant // nplts, ant % nplts].legend() axarr[ant // nplts, ant % nplts].set_title('Antenna '+str(ant_names[ant])) # axarr[ant // nplts, ant % nplts].set_xlabel('Time (Hours)') # axarr[ant // nplts, ant % nplts].set_ylabel('Gain Amplitude') # axarr[ant // nplts, ant % nplts].set_ylim(0,20) axarr[ant // nplts, ant % nplts].set_ylim(globminph-5.0,globmaxph+5.0) for i in range(nplts): for j in range(nplts): if ( ((i*nplts)+(j+1))> N_ants): axarr[i,j].set_visible(False) plot_f = plot_file+"-gain-ph.png" f.savefig(plot_f) plt.close(f) G_tab.close() G_tab_names.close() plt.close('all') def plot_delay_table(gain_table, plt_scale=6, plt_dpi=600, plot_file=None): #Reads in the gain table; makes plots of gain amplitude/phase with #time/frequency for all the antennas. #Read in the table plot_file = plot_file or gain_table+'.png' G_tab = table(gain_table) print(('Reading gain table:', gain_table, '\n')) G_tab_names = table(gain_table+"::ANTENNA") ant_names = G_tab_names.getcol("NAME") print(("Antennas present in the table:", ant_names)) #Get number of antennas (needed for plotting) Ant_n1 = G_tab.getcol("ANTENNA1") Ant_n2 = G_tab.getcol("ANTENNA2") # Ant_list = list(set(np.append(Ant_n1,Ant_n2))) N_ants = len(ant_names) print(('Number of Antennas to plot:', N_ants)) #Read in the flags flags = G_tab.getcol("FLAG") #Read in the solutions Gsols = G_tab.getcol("FPARAM") nchans = Gsols.shape[1] nsols = Gsols.shape[0]//N_ants print(("Number of solutions per antenna:", nsols)) npol = Gsols.shape[2] #Read in the error. Gsols_err = G_tab.getcol("PARAMERR") #Read in the timestamps Gsols_time = G_tab.getcol("TIME") #Prepare for plotting; store gain amp and phases. Gsols_HH = Gsols[:,:,0] Gsols_VV = Gsols[:,:,1] print(("Shape of solutions:", np.shape(Gsols_HH), np.shape(Gsols_VV))) Gsols_HH_plt = np.ma.masked_array(Gsols_HH, mask=flags[:,:,0]) Gsols_VV_plt = np.ma.masked_array(Gsols_VV, mask=flags[:,:,1]) #Plotting #Plot in a more or less square grid. nplts = int(np.sqrt(N_ants))+1 #(if non zero remainder, add one) print(("Number of plots:", nplts*nplts)) #Set Global matplotlib options matplotlib.rcParams['lines.markersize'] = 15.0 matplotlib.rcParams['xtick.major.size'] = 5.0 matplotlib.rcParams['ytick.major.size'] = 5.0 matplotlib.rcParams['ytick.direction'] = 'out' matplotlib.rcParams['xtick.direction'] = 'out' matplotlib.rcParams['font.size'] = 15.0 matplotlib.rcParams['axes.linewidth'] = 3.0 matplotlib.rcParams['legend.framealpha'] = 0.5 matplotlib.rcParams['font.style'] = 'italic' # matplotlib.rcParams['legend.frameon']='false' #Make a single plot for gain amplitude and phase, colourize different fields? obs_time = G_tab.getcol("TIME") #Scale to start time and scale to hours obs_time = obs_time-obs_time[0] obs_time = obs_time/3600.0 f, axarr = plt.subplots(nplts, nplts, dpi=plt_dpi, figsize=(nplts*plt_scale,nplts*plt_scale)) f.text(0.5,0.94,"Delay Calibration Plot",ha='center',fontsize=40) f.text(0.5, 0.04, 'Time (Hours)', ha='center',fontsize=30) f.text(0.04, 0.5, 'Delay (ns)', va='center', rotation='vertical',fontsize=30) globmax = np.round(np.max(np.maximum(Gsols_VV, Gsols_HH)),1) globmin = np.round(np.min(np.minimum(Gsols_VV, Gsols_HH)),1) for ant in range(N_ants): for sol in range(nsols): axarr[ant // nplts, ant % nplts].plot(obs_time[ant+N_ants*sol], Gsols_HH_plt[ant+N_ants*sol],color='#4169E1', marker = '.', label='CORR0') axarr[ant // nplts, ant % nplts].plot(obs_time[ant+N_ants*sol], Gsols_VV_plt[ant+N_ants*sol],color='#FF681F', marker = '.', label='CORR1') if sol==0: axarr[ant // nplts, ant % nplts].legend() axarr[ant // nplts, ant % nplts].set_title('Antenna '+str(ant_names[ant])) # axarr[ant // nplts, ant % nplts].set_xlabel('Time (Hours)') # axarr[ant // nplts, ant % nplts].set_ylabel('Gain Amplitude') # axarr[ant // nplts, ant % nplts].set_ylim(0,20) axarr[ant // nplts, ant % nplts].set_ylim(globmin-0.5,globmax+0.5) for i in range(nplts): for j in range(nplts): if ( ((i*nplts)+(j+1))> N_ants): axarr[i,j].set_visible(False) plot_f = plot_file+"-delay.png" f.savefig(plot_f) plt.close(f) plt.close('all') G_tab.close() G_tab_names.close() def gain_plotter(caltable,typ,outfile,plt_scale=6,plt_dpi=600): #"Plots gaintables. Types should be 'delay', 'gain' or 'bandpass'. Scale is the plot scale, dpi is the plot dpi" if (typ=='delay'): plot_delay_table(caltable,plt_scale,plt_dpi,outfile) elif (typ=='gain'): plot_gain_table(caltable,plt_scale,plt_dpi,outfile) elif (typ=='bandpass'): plot_bandpass_table(caltable,plt_scale,plt_dpi,outfile) else: raise RuntimeError('Gain table type "{}" not recognised'.format(typ))
15,561
40.388298
149
py
msutils
msutils-master/MSUtils/flag_stats.py
#from contextlib import ExitStack import sys import math import json import numpy import logging import casacore.measures from MSUtils import msutils import dask import dask.array as da from daskms import xds_from_ms, xds_to_table, xds_from_table from bokeh.layouts import row, column from bokeh.plotting import figure, output_file, save def create_logger(): """Create a console logger""" log = logging.getLogger(__name__) cfmt = logging.Formatter(('%(name)s - %(asctime)s %(levelname)s - %(message)s')) log.setLevel(logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.INFO) console.setFormatter(cfmt) log.addHandler(console) return log LOGGER = create_logger() def _get_ant_flags(names, antenna1, antenna2, flags): names = names[0] # chan and corr are assumed to have a single chunk # so we contract twice to access this single ndarray flags = flags[0][0] nant = len(names) fracs = numpy.zeros([nant,2], dtype=numpy.float64) for i in range(nant): flag_sum = flags[numpy.logical_or(antenna1==i, antenna2==i)] fracs[i,0] += flag_sum.sum() fracs[i,1] += numpy.product(flag_sum.shape) return fracs def _get_flags(names, flags): names = names[0] # chan and corr are assumed to have a single chunk # so we contract twice to access this single ndarray flags = flags[0][0] num = len(names) # num can be scan, corr, field names fracs = numpy.zeros([num,2], dtype=numpy.float64) for i in range(num): fracs[i,0] = flags.sum() fracs[i,1] = numpy.product(flags.shape) return fracs def _chunk(x, keepdims, axis): return x def _combine(x, keepdims, axis): if isinstance(x, list): return sum(x) elif isinstance(x, numpy.ndarray): return x else: raise TypeError("Invalid type %s" % type(x)) def _aggregate(x, keepdims, axis): return _combine(x, keepdims, axis) def _distance(xyz1, xyz2): """Distance between two points in a three dimension coordinate system""" x = xyz2[0] - xyz1[0] y = xyz2[1] - xyz1[1] z = xyz2[2] - xyz1[2] d2 = (x * x) + (y * y) + (z * z) d = numpy.sqrt(d2) return d def wgs84_to_ecef(lon, lat, alt): """ Convert wgs84(latitude (deg), longitude(deg), elevation(deg)) to Earth Centred Earth fixed coordinates (X(m), Y(m), Z(m)). Coordinates in the ITRF format should be converted to WGS84 coordinate system for consistency. This function is an implementation based on the following reference: https://docs.hisparc.nl/coordinates/HiSPARC_coordinates.pdf Parameters ----------: lat: :obj:`float` Latitude in degrees lon: :obj:`float` Longitude in degrees alt: :obj:`float` Altitude in metres Returns ------- X, Y, Z: ECEF coordinates in metres """ # set up earth's shape ellipsoid approximation # semi major axis a = 6378137.0 # flattening f = 1 / 298.257223563 # semi-minor axis b = a - a * f # eccentricity e = numpy.sqrt((2 * f) - (f**2)) # Normal: Distance between a location on the ellipsoid and the # intersection of its nromal and the ellipsoid's z-axis N = a / numpy.sqrt(1 - e**2 * numpy.sin(lat)**2) # altitude h = alt # transformation X = (N + h) * numpy.cos(lat) * numpy.cos(lon) Y = (N + h) * numpy.cos(lat) * numpy.sin(lon) Z = (((b**2 / a**2) * N) + h) * numpy.sin(lat) return X, Y, Z def antenna_flags_field(msname, fields=None, antennas=None): ds_ant = xds_from_table(msname+"::ANTENNA")[0] ds_field = xds_from_table(msname+"::FIELD")[0] ds_obs = xds_from_table(msname+"::OBSERVATION")[0] ant_names = ds_ant.NAME.data.compute() field_names = ds_field.NAME.data.compute() ant_positions = ds_ant.POSITION.data.compute() LOGGER.info("Computing antenna flag stats data...") LOGGER.info(f"Antenna Names: {ant_names}") try: # Get observatory name and array centre obs_name = ds_obs.TELESCOPE_NAME.data.compute()[0] LOGGER.info(f"Observatory Name: {obs_name}") me = casacore.measures.measures() obs_cofa = me.observatory(obs_name) lon, lat, alt = (obs_cofa['m0']['value'], obs_cofa['m1']['value'], obs_cofa['m2']['value']) cofa = wgs84_to_ecef(lon, lat, alt) except: # Otherwise use the first id antenna as array centre LOGGER.warn("Using the first id antenna as array centre.") cofa = ant_positions[0] if fields: if isinstance(fields[0], str): field_ids = list(map(fields.index, fields)) else: field_ids = fields else: field_ids = list(range(len(field_names))) if antennas: if isinstance(antennas[0], str): ant_ids = list(map(antennas.index, antennas)) else: ant_ids = antennas else: ant_ids = list(range(len(ant_names))) nant = len(ant_ids) nfield = len(field_ids) fields_str = ", ".join(map(str, field_ids)) ds_mss = xds_from_ms(msname, group_cols=["FIELD_ID", "DATA_DESC_ID"], chunks={'row': 100000}, taql_where="FIELD_ID IN [%s]" % fields_str) flag_sum_computes = [] for ds in ds_mss: flag_sums = da.blockwise(_get_ant_flags, ("row",), ant_ids, ("ant",), ds.ANTENNA1.data, ("row",), ds.ANTENNA2.data, ("row",), ds.FLAG.data, ("row","chan", "corr"), adjust_chunks={"row": nant }, dtype=numpy.ndarray) flags_redux = da.reduction(flag_sums, chunk=_chunk, combine=_combine, aggregate=_aggregate, concatenate=False, dtype=numpy.float64) flag_sum_computes.append(flags_redux) #flag_sum_computes[0].visualize("graph.pdf") sum_per_field_spw = dask.compute(flag_sum_computes)[0] sum_all = sum(sum_per_field_spw) fractions = sum_all[:,0]/sum_all[:,1] stats = {} for i,aid in enumerate(ant_ids): ant_stats = {} ant_pos = list(ant_positions[i]) ant_stats["name"] = ant_names[aid] ant_stats["position"] = ant_pos ant_stats["array_centre_dist"] = _distance(cofa, ant_pos) ant_stats["frac"] = fractions[i] ant_stats["sum"] = sum_all[i][0] ant_stats["counts"] = sum_all[i][1] stats[aid] = ant_stats return stats def scan_flags_field(msname, fields=None): ds_field = xds_from_table(msname+"::FIELD")[0] ds_obs = xds_from_table(msname+"::OBSERVATION")[0] field_names = ds_field.NAME.data.compute() LOGGER.info("Computing scan flag stats data...") if fields: if isinstance(fields[0], str): field_ids = list(map(fields.index, fields)) else: field_ids = fields else: field_ids = list(range(len(field_names))) fields_str = ", ".join(map(str, field_ids)) ds_mss = xds_from_ms(msname, group_cols=["SCAN_NUMBER"], chunks={'row': 100000}, taql_where="FIELD_ID IN [%s]" % fields_str) flag_sum_computes = [] scan_ids = list(range(len(ds_mss))) scan_names = [str(ds.SCAN_NUMBER) for ds in ds_mss] nscans = len(scan_ids) LOGGER.info(f"Scan Names: {scan_names}") for ds in ds_mss: flag_sums = da.blockwise(_get_flags, ("row",), scan_ids, ("scan",), ds.FLAG.data, ("row","chan", "corr"), adjust_chunks={"row": nscans }, dtype=numpy.ndarray) flags_redux = da.reduction(flag_sums, chunk=_chunk, combine=_combine, aggregate=_aggregate, concatenate=False, dtype=numpy.float64) flag_sum_computes.append(flags_redux) sum_per_scan_spw = dask.compute(flag_sum_computes)[0] stats = {} for i,sid in enumerate(scan_ids): scan_stats = {} sum_all = sum(sum_per_scan_spw[i]) fraction = sum_all[0]/sum_all[1] scan_stats["name"] = scan_names[sid] scan_stats["frac"] = fraction scan_stats["sum"] = sum_all[0] scan_stats["counts"] = sum_all[1] stats[sid] = scan_stats return stats def source_flags_field(msname, fields=None): ds_field = xds_from_table(msname+"::FIELD")[0] ds_obs = xds_from_table(msname+"::OBSERVATION")[0] field_names = ds_field.NAME.data.compute() LOGGER.info("Computing field flag stats data...") LOGGER.info(f"Field Names: {field_names}") if fields: if isinstance(fields[0], str): field_ids = list(map(list(field_names).index, fields)) else: field_ids = fields else: field_ids = list(range(len(field_names))) fields_str = ", ".join(map(str, field_ids)) ds_mss = xds_from_ms(msname, group_cols=["FIELD_ID"], chunks={'row': 100000}, taql_where="FIELD_ID IN [%s]" % fields_str) flag_sum_computes = [] nfields = len(field_ids) for ds in ds_mss: flag_sums = da.blockwise(_get_flags, ("row",), field_ids, ("field",), ds.FLAG.data, ("row","chan", "corr"), adjust_chunks={"row": nfields}, dtype=numpy.ndarray) flags_redux = da.reduction(flag_sums, chunk=_chunk, combine=_combine, aggregate=_aggregate, concatenate=False, dtype=numpy.float64) flag_sum_computes.append(flags_redux) sum_per_field_spw = dask.compute(flag_sum_computes)[0] stats = {} for i,fid in enumerate(field_ids): field_stats = {} sum_all = sum(sum_per_field_spw[i]) fraction = sum_all[0]/sum_all[1] field_stats["name"] = field_names[fid] field_stats["frac"] = fraction field_stats["sum"] = sum_all[0] field_stats["counts"] = sum_all[1] stats[fid] = field_stats return stats def correlation_flags_field(msname, fields=None): ds_field = xds_from_table(msname+"::FIELD")[0] ds_obs = xds_from_table(msname+"::OBSERVATION")[0] ds_pols = xds_from_table(msname+"::POLARIZATION")[0] corr_names = [msutils.STOKES_TYPES[corr] for corr in list(ds_pols.CORR_TYPE.data.compute()[0])] field_names = ds_field.NAME.data.compute() corr_ids = list(range(len(corr_names))) ncorrs = len(corr_ids) LOGGER.info("Computing correlation flag stats data...") LOGGER.info(f"Correlation Names: {corr_names}") if fields: if isinstance(fields[0], str): field_ids = list(map(list(field_names).index, fields)) else: field_ids = fields else: field_ids = list(range(len(field_names))) fields_str = ", ".join(map(str, field_ids)) ds_mss = xds_from_ms(msname, group_cols=["DATA_DESC_ID"], chunks={'row': 100000}, taql_where="FIELD_ID IN [%s]" % fields_str) flag_sum_computes = [] nfields = len(field_ids) for ds in ds_mss: flag_sums = da.blockwise(_get_flags, ("row",), corr_ids, ("corr",), ds.FLAG.data, ("row", "chan", "corr"), adjust_chunks={"corr": ncorrs}, dtype=numpy.ndarray) flags_redux = da.reduction(flag_sums, chunk=_chunk, combine=_combine, aggregate=_aggregate, concatenate=False, dtype=numpy.float64) flag_sum_computes.append(flags_redux) sum_per_corr_spw = dask.compute(flag_sum_computes)[0] stats = {} for i,cid in enumerate(corr_ids): corr_stats = {} sum_all = [sum_per_corr_spw[0][i][0], sum_per_corr_spw[0][i][1]] fraction = sum_all[0]/sum_all[1] corr_stats["name"] = corr_names[cid] corr_stats["frac"] = fraction corr_stats["sum"] = sum_all[0] corr_stats["counts"] = sum_all[1] stats[cid] = corr_stats return stats def _plot_flag_stats(antenna_stats, scan_stats, target_stats, corr_stats, outfile=None): """Plot antenna, corr, scan or target summary flag stats""" LOGGER.info("Plotting flag stats data.") plots={ 'fields': {'title':'Field RFI summary', 'x_label': 'Field', 'y_label': 'Flagged data (%)', 'rotate_xlabel':False}, 'antennas': {'title':'Antenna RFI summary', 'x_label': 'Antenna', 'y_label': 'Flagged data (%)', 'rotate_xlabel':True}, 'scans': {'title':'Scans RFI summary', 'x_label': 'Scans', 'y_label': 'Flagged data (%)', 'rotate_xlabel':True}, 'corrs': {'title':'Correlation RFI summary', 'x_label': 'Correlation', 'y_label': 'Flagged data (%)', 'rotate_xlabel':False} } plot_list = [] if not outfile: outfile = 'default-flagging-summary-plots.html' for flag_stats in [antenna_stats, scan_stats, target_stats, corr_stats]: key = list(flag_stats.keys())[0] flag_data = list(flag_stats.values())[0] stats_keys = [fd['name'] for fd in flag_data.values()] flag_percentages = [fd['frac']*100 for fd in flag_data.values()] rotate_xlabel = plots[key]['rotate_xlabel'] x_label=plots[key]['x_label'] y_label=plots[key]['y_label'] title=plots[key]['title'] plotter = figure(x_range=stats_keys, x_axis_label=x_label, y_axis_label=y_label, plot_width=600, plot_height=400, title=title, y_range=(0, 100), tools="hover,box_zoom,wheel_zoom,pan,save,reset") plotter.vbar(x=stats_keys, top=flag_percentages, width=0.9) plotter.xgrid.grid_line_color = None plotter.y_range.start = 0 plotter.title.align = 'center' plotter.hover.tooltips = [(key.title(), "@x"), ("%", "@top")] if rotate_xlabel: plotter.xaxis.major_label_orientation = math.pi/2 plot_list.append(plotter) output_file(outfile) LOGGER.info(f"Output plots: {outfile}.") save(column(row(plot_list[2], plot_list[3]), row(plot_list[1], plot_list[0]))) def plot_statistics(msname, antennas=None, fields=None, htmlfile=None, outfile=None): """Plot stats data""" flag_data = save_statistics(msname, antennas=antennas, fields=fields, outfile=outfile) _plot_flag_stats(**flag_data, outfile=htmlfile) def save_statistics(msname, antennas=None, fields=None, outfile=None): """Save flag statistics to a json file""" target_stats = {'fields': source_flags_field(msname, fields)} scan_stats = {'scans': scan_flags_field(msname, fields)} antenna_stats = {'antennas': antenna_flags_field(msname, fields, antennas)} corr_stats = {'corrs': correlation_flags_field(msname, fields)} flag_data = {'Flag stats': [scan_stats, antenna_stats, target_stats, corr_stats]} if not outfile: outfile = 'default-flag-statistics.json' LOGGER.info(f'Output json file: {outfile}.') with open(outfile, 'w') as f: json.dump(flag_data, f) flag_data = {'antenna_stats': antenna_stats, 'scan_stats': scan_stats, 'target_stats': target_stats, 'corr_stats': corr_stats} return flag_data #with ExitStack() as stack: # from dask.diagnostics import Profiler, visualize # prof = Profiler() # # stack.enter_context(prof) # result = dask.compute(writes)[0] # print(sum(result)) # # import pdb; pdb.set_trace() # # visualize(prof)
16,577
35.676991
99
py
msutils
msutils-master/MSUtils/__init__.py
from MSUtils import msutils
28
13.5
27
py
msutils
msutils-master/MSUtils/ClassESW.py
import matplotlib matplotlib.use('Agg') import sys import os import numpy import numpy.ma as ma import pylab from scipy.interpolate import interp1d from scipy import interpolate from MSUtils import msutils from pyrap.tables import table import matplotlib.cm as cm MEERKAT_SEFD = numpy.array([ [ 856e6, 580.], [ 900e6, 578.], [ 950e6, 559.], [1000e6, 540.], [1050e6, 492.], [1100e6, 443.], [1150e6, 443.], [1200e6, 443.], [1250e6, 443.], [1300e6, 453.], [1350e6, 443.], [1400e6, 424.], [1450e6, 415.], [1500e6, 405.], [1550e6, 405.], [1600e6, 405.], [1650e6, 424.], [1711e6, 421.]], dtype=numpy.float32) class MSNoise(object): """ Estimates visibility noise statistics as a function of frequency given a measurement set (MS). This statistics can be used to generate weights which can be saved in the MS. """ def __init__(self, ms): """ Args: ms (Directory, CASA Table): CASA measurement set """ self.ms = ms # First get some basic info about the Ms self.msinfo = msutils.summary(self.ms, display=False) self.nrows = self.msinfo['NROW'] self.ncor = self.msinfo['NCOR'] self.spw = { "freqs" : self.msinfo['SPW']['CHAN_FREQ'], "nchan" : self.msinfo['SPW']['NUM_CHAN'], } self.nspw = len(self.spw['freqs']) def estimate_noise(self, corr=None, autocorr=False): """ Estimate visibility noise """ return def estimate_weights(self, mode='specs', stats_data=None, normalise=True, smooth='polyn', fit_order=9, plot_stats=True): """ Args: mode (str, optional): Mode for estimating noise statistics. These are the options: - specs : This is a file or array of values that are proportional to the sensitivity as a function of frequency. For example SEFD values. Column one should be the frequency, and column two should be the sensitivity. - calc : Calculate noise internally. The calculations estimates the noise by taking differences between adjacent channels. noise_data (file, list, numpy.ndarray): File or array containing information about sensitivity as a function of frequency (in Hz) smooth (str, optional): Generate a smooth version of the data. This version is used for further calculations. Options are: - polyn : Smooth with a polynomial. This is the dafualt - spline : Smooth with a spline fit_order (int, optional): Oder for function used to smooth the data. Default is 9 """ #TODO(sphe): add function to estimate noise for the other mode. # For now, fix the mode mode = 'specs' if mode=='specs': if isinstance(stats_data, str): __data = numpy.load(stats_data) else: __data = numpy.array(stats_data, dtype=numpy.float32) x,y = __data[:,0], __data[:,1] elif mode=='calc': # x,y = self.estimate_noise() pass if normalise: y /= y.max() # lets work in MHz x = x*1e-6 if smooth=='polyn': fit_parms = numpy.polyfit(x, y, fit_order) fit_func = lambda freqs: numpy.poly1d(fit_parms)(freqs) elif smooth=='spline': fit_parms = interpolate.splrep(x, y, s=fit_order) fit_func = lambda freqs: interpolate.splev(freqs, fit_parms, der=0) # Get noise from the parameterised functions for each spectral window fig, ax1 = pylab.subplots(figsize=(12,9)) ax2 = ax1.twinx() color = iter(cm.rainbow(numpy.linspace(0,1,self.nspw))) noise = [] weights = [] for i in range(self.nspw): freqs = numpy.array(self.spw['freqs'][i], dtype=numpy.float32)*1e-6 _noise = fit_func(freqs) _weights = 1.0/_noise**2 if plot_stats: # Use a differnet color to mark a new SPW ax1.axvspan(freqs[0]/1e3, freqs[-1]/1e3, facecolor=next(color), alpha=0.25) # Plot noise/weights l1, = ax1.plot(x/1e3, y, 'rx') l2, = ax1.plot(freqs/1e3, _noise, 'k-') ax1.set_xlabel('Freq [GHz]') ax1.set_ylabel('Norm Noise') l3, = ax2.plot(freqs/1e3, _weights, 'g-') ax2.set_ylabel('Weight') noise.append(_noise) weights.append(_weights) # Set limits based on non-smooth noise ylims = 1/y**2 ax2.set_ylim(ylims.min()*0.9, ylims.max()*1.1) pylab.legend([l1,l2,l3], ['Norm. Noise', 'Polynomial fit: n={0:d}'.format(fit_order), 'Weights'], loc=1) if isinstance(plot_stats, str): pylab.savefig(plot_stats) else: pylab.savefig(self.ms + '-noise_weights.png') pylab.clf() return noise, weights def write_toms(self, data, columns=['WEIGHT', 'WEIGHT_SPECTRUM'], stat='sum', rowchunk=None, multiply_old_weights=False): """ Write noise or weights into an MS. Args: columns (list): columns to write weights/noise and spectral counterparts into. Default is columns = ['WEIGHT', 'WEIGHT_SPECTRUM'] stat (str): Statistic to compute when combining data along frequency axis. For example, used the sum along Frequency axis of WEIGHT_SPECTRUM as weight for the WEIGHT column """ # Initialise relavant columns. It will exit with zero status if the column alredy exists for i, column in enumerate(columns): msutils.addcol(self.ms, colname=column, valuetype='float', clone='WEIGHT' if i==0 else 'DATA', ) for spw in range(self.nspw): tab = table(self.ms, readonly=False) # Write data into MS in chunks rowchunk = rowchunk or self.nrows/10 for row0 in range(0, self.nrows, rowchunk): nr = min(rowchunk, self.nrows-row0) # Shape for this chunk dshape = [nr, self.spw['nchan'][spw], self.ncor] __data = numpy.ones(dshape, dtype=numpy.float32) * data[spw][numpy.newaxis,:,numpy.newaxis] # Consider old weights if user wants to if multiply_old_weights: old_weight = tab.getcol('WEIGHT', row0, nr) print("Multiplying old weights into WEIGHT_SPECTRUM") __data *= old_weight[:,numpy.newaxis,:] # make a masked array to compute stats using unflagged data flags = tab.getcol('FLAG', row0, nr) mdata = ma.masked_array(__data, mask=flags) print(("Populating {0:s} column (rows {1:d} to {2:d})".format(columns[1], row0, row0+nr-1))) tab.putcol(columns[1], __data, row0, nr) print(("Populating {0:s} column (rows {1:d} to {2:d})".format(columns[0], row0, row0+nr-1))) if stat=="stddev": tab.putcol(columns[0], mdata.std(axis=1).data, row0, nr) elif stat=="sum": tab.putcol(columns[0], mdata.sum(axis=1).data, row0, nr) # Done tab.close()
7,690
36.517073
131
py
ssci2022
ssci2022-main/run2.py
from sys import argv from psb import program_synth as ps from garch import genome_archive_part as gap problem, search, npop, ngen, nproc, seed = argv[1:] garch = gap(["small-or-large/1017.sol", "median/1010.sol"], n_part=5) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.0, adaptation_rate=0.0, savepop=f"{problem}/{seed}.hst") est.save(f"{problem}/{seed}.sol")
614
24.625
69
py
ssci2022
ssci2022-main/run3.py
from sys import argv from pyshgp.gp.genome import Genome, GenomeArchive from pyshgp.gp.individual import Individual from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] sl = Individual.load("small-or-large/1017.sol").genome md = Individual.load("median/1010.sol").genome garch = GenomeArchive([ sl[:3], sl[3:5], sl[5:8], sl[8:10], sl[10:], md[:2], md[2:3], md[5:6], md[6:9], md[9:] ]) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5, savepop=f"{problem}/{seed}.hst") est.save(f"{problem}/{seed}.sol")
818
26.3
54
py
ssci2022
ssci2022-main/psb.py
import string import numpy as np import pandas as pd import time from pyshgp.gp.estimators import PushEstimator from pyshgp.gp.genome import GeneSpawner from pyshgp.push.config import PushConfig from pyshgp.push.instruction_set import InstructionSet from pyshgp.push.types import Char, IntVector, FloatVector, StrVector class _PSB1: def __init__(self, name, edge, rand, test, root="psb", seed=None): self.edge_path = root + "/" + name + "/" + name + "-edge.json" self.rand_path = root + "/" + name + "/" + name + "-random.json" self.edg = edge self.rnd = rand self.tst = test self.seed = seed def process_type(self, dat): return dat @property def train(self): edge = pd.read_json(self.edge_path, orient="records", lines=True, precise_float=True).sample(self.edg, replace=False, random_state=self.seed, ignore_index=True) rand = pd.read_json(self.rand_path, orient="records", lines=True, precise_float=True).sample(self.rnd, replace=False, random_state=self.seed, ignore_index=True) dat = pd.concat([edge, rand], ignore_index=True) dat = self.process_type(dat) inputs = [] outputs = [] for col in dat.columns: if "input" in col: inputs.append(col) else: outputs.append(col) inp, out = dat[inputs], dat[outputs] return inp, out @property def test(self): dat = pd.read_json(self.rand_path, orient="records", lines=True, precise_float=True).sample(self.tst, replace=False, random_state=self.seed+1000, ignore_index=True) dat = self.process_type(dat) inputs = [] outputs = [] for col in dat.columns: if "input" in col: inputs.append(col) else: outputs.append(col) inp, out = dat[inputs], dat[outputs] return inp, out # PSB1 Problems class Checksum(_PSB1): def __init__(self, name="checksum", edge=106, rand=194, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=1500) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=["Check sum is ", Char(" "), 64], erc_generators=[self.random_integer_128, self.random_char_visible] ) def random_integer_128(self): return np.random.randint(-128,129) def random_char_visible(self): visible = string.digits + string.ascii_letters + string.punctuation + "\n\t" return Char(np.random.choice(visible)) class CollatzNumbers(_PSB1): def __init__(self, name="collatz-numbers", edge=16, rand=184, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000000 self.max_genome_size = 2400 self.initial_genome_size = (60, 300) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=15000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "float", "bool"}), literals=[0, 1], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(-100,101) class CompareStringLengths(_PSB1): def __init__(self, name="compare-string-lengths", edge=22, rand=78, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1 self.max_genome_size = 1600 self.initial_genome_size = (40, 200) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=600) @property def spawner(self): return GeneSpawner( n_inputs=3, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str"}), literals=[], erc_generators=[self.random_boolean] ) def random_boolean(self): return np.random.choice([True, False]) class CountOdds(_PSB1): def __init__(self, name="count-odds", edge=32, rand=168, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000 self.max_genome_size = 2000 self.initial_genome_size = (50, 250) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=1500) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "vector_int"}), literals=[0,1,2], erc_generators=[self.random_integer_1000] ) def random_integer_1000(self): return np.random.randint(-1000, 1001) def process_type(self, dat): dat["input1"] = [IntVector(item) for item in dat.input1] return dat class Digits(_PSB1): def __init__(self, name="digits", edge=15, rand=85, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 1200 self.initial_genome_size = (30, 150) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=600) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=[Char("\n")], erc_generators=[self.random_integer_10] ) def random_integer_10(self): return np.random.randint(-10, 10) class DoubleLetters(_PSB1): def __init__(self, name="double-letters", edge=32, rand=68, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=1600) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=[Char("!")], erc_generators=[] ) class EvenSquares(_PSB1): def __init__(self, name="even-squares", edge=17, rand=83, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 1600 self.initial_genome_size = (40, 200) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=2000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "stdout"}), literals=[], erc_generators=[] ) class ForLoopIndex(_PSB1): def __init__(self, name="for-loop-index", edge=10, rand=90, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 1200 self.initial_genome_size = (30, 150) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=600) @property def spawner(self): return GeneSpawner( n_inputs=3, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "stdout"}), literals=[], erc_generators=[] ) class Grade(_PSB1): def __init__(self, name="grade", edge=41, rand=159, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 1600 self.initial_genome_size = (40, 200) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=800) @property def spawner(self): return GeneSpawner( n_inputs=5, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str", "stdout"}), literals=["Student has a ", " grade.", "A", "B", "C", "D", "F"], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(0, 101) class LastIndexOfZero(_PSB1): def __init__(self, name="last-index-of-zero", edge=72, rand=78, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000000 self.max_genome_size = 1200 self.initial_genome_size = (30, 150) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=600) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "vector_int"}), literals=[0], erc_generators=[] ) def process_type(self, dat): dat["input1"] = [IntVector(item) for item in dat.input1] return dat class Median(_PSB1): def __init__(self, name="median", edge=0, rand=100, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=200) @property def spawner(self): return GeneSpawner( n_inputs=3, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "stdout"}), literals=[], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(-100, 101) def process_type(self, dat): dat["output1"] = [str(item) for item in dat.output1] return dat class MirrorImage(_PSB1): def __init__(self, name="mirror-image", edge=23, rand=77, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1 self.max_genome_size = 1200 self.initial_genome_size = (30, 150) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=600) @property def spawner(self): return GeneSpawner( n_inputs=2, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "vector_int"}), literals=[], erc_generators=[self.random_boolean] ) def random_boolean(self): return np.random.choice([True, False]) def process_type(self, dat): dat["output1"] = [IntVector(item) for item in dat.output1] dat["output2"] = [IntVector(item) for item in dat.output2] return dat class NegativeToZero(_PSB1): def __init__(self, name="negative-to-zero", edge=17, rand=183, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 2000 self.initial_genome_size = (50, 250) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=1500) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "vector_int"}), literals=[0, IntVector()], erc_generators=[] ) def process_type(self, dat): dat["input1"] = [IntVector(item) for item in dat.input1] dat["output1"] = [IntVector(item) for item in dat.output1] return dat class NumberIO(_PSB1): def __init__(self, name="number-io", edge=0, rand=25, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 1e-04 self.penalty = 5000 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=200) @property def spawner(self): return GeneSpawner( n_inputs=2, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "float", "stdout"}), literals=[], erc_generators=[self.random_integer_100, self.random_float_100] ) def random_integer_100(self): return np.random.randint(-100, 101) def random_float_100(self): return np.random.uniform(-100, 100) def process_type(self, dat): dat["output1"] = [str(item) for item in dat.output1] return dat class PigLatin(_PSB1): def __init__(self, name="pig-latin", edge=33, rand=167, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 4000 self.initial_genome_size = (100, 500) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=2000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=["ay", Char(" "), Char("a"), Char("e"), Char("i"), Char("o"), Char("u"), "aeiou"], erc_generators=[self.random_char_visible, self.random_input_20] ) def random_char_visible(self): visible = string.digits + string.ascii_letters + string.punctuation + "\n\t" return Char(np.random.choice(visible)) def random_input_20(self): length = np.random.randint(0, 21) return self._input(length) def _input(self, length): lower = string.ascii_lowercase tmp = [] for _ in range(length): if np.random.random() < 0.2: tmp.append(" ") else: l = lower[np.random.randint(0,len(lower))] tmp.append(l) s = "".join(tmp) tmp_lst = s.split(" ") tmp_lst_ = [] for item in tmp_lst: if item != "": tmp_lst_.append(item) s = " ".join(tmp_lst_) return s class ReplaceSpaceWithNewline(_PSB1): def __init__(self, name="replace-space-with-newline", edge=30, rand=70, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=1600) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=[Char(" "), Char("\n")], erc_generators=[self.random_char_visible, self.random_input_20] ) def random_char_visible(self): visible = string.digits + string.ascii_letters + string.punctuation + "\n\t" return Char(np.random.choice(visible)) def random_input_20(self): length = np.random.randint(0, 21) return self._input(length) def _input(self, length): visible = string.digits + string.ascii_letters + string.punctuation tmp = [] for _ in range(length): if np.random.random() < 0.2: tmp.append(" ") else: l = visible[np.random.randint(0,len(visible))] tmp.append(l) s = "".join(tmp) return s class ScrabbleScore(_PSB1): def __init__(self, name="scrabble-score", edge=50, rand=150, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000 self.max_genome_size = 4000 self.initial_genome_size = (100, 500) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=2000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "vector_int"}), literals=[IntVector(self.scrabble_vector)], erc_generators=[] ) @property def scrabble_vector(self): vec = [0] * 127 letter_score = [1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10] for i, score in enumerate(letter_score): vec[i+65] = vec[i+97] = score return vec class SmallOrLarge(_PSB1): def __init__(self, name="small-or-large", edge=27, rand=73, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=300) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str", "stdout"}), literals=["small", "large"], erc_generators=[self.random_integer_10000] ) def random_integer_10000(self): return np.random.randint(-10000, 10001) class Smallest(_PSB1): def __init__(self, name="smallest", edge=5, rand=95, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=200) @property def spawner(self): return GeneSpawner( n_inputs=4, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "stdout"}), literals=[], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(-100, 101) def process_type(self, dat): dat["output1"] = [str(item) for item in dat.output1] return dat class StringDifferences(_PSB1): def __init__(self, name="string-differences", edge=30, rand=170, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 4000 self.initial_genome_size = (100, 500) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=2000) @property def spawner(self): return GeneSpawner( n_inputs=2, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=[Char(" "), Char("\n")], erc_generators=[self.random_integer_10] ) def random_integer_10(self): return np.random.randint(-10, 11) class StringLengthsBackwards(_PSB1): def __init__(self, name="string-lengths-backwards", edge=10, rand=90, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 1200 self.initial_genome_size = (30, 150) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=600) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str", "vector_str", "stdout"}), literals=[], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(-100, 101) def process_type(self, dat): dat["input1"] = [StrVector(item) for item in dat.input1] return dat class SumOfSquares(_PSB1): def __init__(self, name="sum-of-squares", edge=6, rand=44, test=100, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000000000 self.max_genome_size = 1600 self.initial_genome_size = (40, 200) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=4000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool"}), literals=[0, 1], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(-100, 101) class SuperAnagrams(_PSB1): def __init__(self, name="super-anagrams", edge=30, rand=170, test=2000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=1600) @property def spawner(self): return GeneSpawner( n_inputs=2, instruction_set=InstructionSet().register_core_by_stack({"exec", "bool", "char", "str"}), literals=[], erc_generators=[self.random_boolean, self.random_char_visible, self.random_integer_1000] ) def random_boolean(self): return np.random.choice([True, False]) def random_char_visible(self): visible = string.digits + string.ascii_letters + string.punctuation + "\n\t" return Char(np.random.choice(visible)) def random_integer_1000(self): return np.random.randint(-1000, 1001) class Syllables(_PSB1): def __init__(self, name="syllables", edge=17, rand=83, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=1600) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=["The number of syllables is ", "aeiouy", Char("a"), Char("e"), Char("i"), Char("o"), Char("u"), Char("y")], erc_generators=[self.random_char_visible, self.random_input_20] ) def random_char_visible(self): visible = string.digits + string.ascii_letters + string.punctuation + "\n\t" return Char(np.random.choice(visible)) def random_input_20(self): length = np.random.randint(0, 21) return self._input(length) def _input(self, length): letters = string.digits + string.ascii_lowercase + string.punctuation + " " tmp = [] for _ in range(length): if np.random.random() < 0.2: l = np.random.choice(["a", "e", "i", "o" ,"u", "y"]) else: l = letters[np.random.randint(0, len(letters))] tmp.append(l) s = "".join(tmp) return s class VectorAverage(_PSB1): def __init__(self, name="vector-average", edge=10, rand=240, test=2550, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 1e-03 self.penalty = 1000000 self.max_genome_size = 1600 self.initial_genome_size = (40, 200) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=800) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "float", "vector_float"}), literals=[], erc_generators=[] ) def process_type(self, dat): dat["input1"] = [FloatVector(item) for item in dat.input1] return dat class VectorsSummed(_PSB1): def __init__(self, name="vectors-summed", edge=15, rand=135, test=1500, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1000000000 self.max_genome_size = 2000 self.initial_genome_size = (50, 250) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=1500) @property def spawner(self): return GeneSpawner( n_inputs=2, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "vector_int"}), literals=[IntVector()], erc_generators=[self.random_integer_1000] ) def random_integer_1000(self): return np.random.randint(-1000, 1001) def process_type(self, dat): dat["input1"] = [FloatVector(item) for item in dat.input1] dat["input2"] = [FloatVector(item) for item in dat.input2] dat["output1"] = [FloatVector(item) for item in dat.output1] return dat class WallisPi(_PSB1): def __init__(self, name="wallis-pi", edge=15, rand=135, test=50, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 1e-03 self.penalty = 1000000.0 self.max_genome_size = 2400 self.initial_genome_size = (60, 300) self.simplification_steps = 5000 self.last_str_from_stdout = False self.push_config = PushConfig(step_limit=8000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "float", "bool"}), literals=[], erc_generators=[self.random_integer_500, self.random_integer_10, self.random_float_500, self.random_float_1] ) def random_integer_500(self): return np.random.randint(-500, 501) def random_integer_10(self): return np.random.randint(-10, 11) def random_float_500(self): return np.random.uniform(-500, 500) def random_float_1(self): return np.random.uniform(0, 1) class WordStats(_PSB1): def __init__(self, name="word-stats", edge=36, rand=64, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.02 self.penalty = 10000 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=6000) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "float", "bool", "char", "str", "vector_int", "vector_float", "vector_str"}), literals=[Char("."), Char("?"), Char("!"), Char(" "), Char("\t"), Char("\n"), IntVector(), FloatVector(), StrVector(), "words of length ", ": ", "number of sentences: ", "average sentence length: "], erc_generators=[self.random_integer_100] ) def random_integer_100(self): return np.random.randint(-100, 101) class XWordLines(_PSB1): def __init__(self, name="x-word-lines", edge=46, rand=104, test=1000, root="psb", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 3200 self.initial_genome_size = (80, 400) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=1600) @property def spawner(self): return GeneSpawner( n_inputs=2, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "char", "str", "stdout"}), literals=[Char(" "), Char("\n")], erc_generators=[] ) # Used-Defined Problems class SmallOrLargeString(_PSB1): def __init__(self, name="small-or-large-string", edge=26, rand=74, test=1000, root="psbext", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=300) @property def spawner(self): return GeneSpawner( n_inputs=1, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str", "stdout"}), literals=["small", "large"], erc_generators=[self.random_integer_1000p] ) def random_integer_1000p(self): return np.random.randint(0, 1001) class MedianStringLength(_PSB1): def __init__(self, name="median-string-length", edge=0, rand=100, test=1000, root="psbext", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 1 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=200) @property def spawner(self): return GeneSpawner( n_inputs=3, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str", "stdout"}), literals=[], erc_generators=[self.random_integer_100p, self.random_boolean] ) def random_integer_100p(self): return np.random.randint(0, 101) def random_boolean(self): return np.random.choice([True, False]) def process_type(self, dat): dat["output1"] = [str(item) for item in dat.output1] return dat class SmallOrLargeMedian(_PSB1): def __init__(self, name="small-or-large-median", edge=0, rand=100, test=1000, root="psbext", seed=None): super().__init__(name, edge, rand, test, root, seed) self.error_threshold = 0.0 self.penalty = 5000 self.max_genome_size = 800 self.initial_genome_size = (20, 100) self.simplification_steps = 5000 self.last_str_from_stdout = True self.push_config = PushConfig(step_limit=300) @property def spawner(self): return GeneSpawner( n_inputs=4, instruction_set=InstructionSet().register_core_by_stack({"exec", "int", "bool", "str", "stdout"}), literals=["small", "large"], erc_generators=[self.random_integer_1000p, self.random_integer_100] ) def random_integer_1000p(self): return np.random.randint(0, 1001) def random_integer_100(self): return np.random.randint(-100, 101) # Problem Sets __problem_set = { "checksum": Checksum, "count-odds": CountOdds, "even-squares": EvenSquares, "last-index-of-zero": LastIndexOfZero, "negative-to-zero": NegativeToZero, "replace-space-with-newli": ReplaceSpaceWithNewline, "small-or-large": SmallOrLarge, "sum-of-squares": SumOfSquares, "vector-average": VectorAverage, "word-stats": WordStats, "collatz-numbers": CollatzNumbers, "digits": Digits, "for-loop-index": ForLoopIndex, "median": Median, "number-io": NumberIO, "scrabble-score": ScrabbleScore, "string-differences": StringDifferences, "super-anagrams": SuperAnagrams, "vectors-summed": VectorsSummed, "x-word-lines": XWordLines, "compare-string-lengths": CompareStringLengths, "double-letters": DoubleLetters, "grade": Grade, "mirror-image": MirrorImage, "pig-latin": PigLatin, "smallest": Smallest, "string-lengths-backwards": StringLengthsBackwards, "syllables": Syllables, "wallis-pi": WallisPi, } __problem_set_ext = { "small-or-large-string": SmallOrLargeString, "median-string-length": MedianStringLength, "small-or-large-median": SmallOrLargeMedian, } def program_synth(problem, search="GA", npop=1000, ngen=300, nproc=False, seed=None, **kwargs): if __problem_set.get(problem): problem = __problem_set.get(problem) elif __problem_set_ext.get(problem): problem = __problem_set_ext.get(problem) else: raise Exception(f"Cannot find problem {problem}.") problem = problem(seed=seed) est = PushEstimator( spawner=problem.spawner, search=search, population_size=npop, max_generations=ngen, push_config=problem.push_config, error_threshold=problem.error_threshold, penalty=problem.penalty, max_genome_size=problem.max_genome_size, initial_genome_size=problem.initial_genome_size, last_str_from_stdout=problem.last_str_from_stdout, parallelism=nproc, verbose=2, **kwargs ) start = time.time() est.fit(*(problem.train)) end = time.time() print("========================================") print("post-evolution stats") print("========================================") print("Runtime: ", end - start) test_score = np.sum(est.score(*(problem.test))) print("Test error:", test_score) return est
36,951
33.025783
211
py
ssci2022
ssci2022-main/run.py
from sys import argv import numpy as np from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed)) est.save(f"{problem}/{seed}.sol")
374
19.833333
51
py
ssci2022
ssci2022-main/garch.py
from typing import Sequence import numpy as np from pyshgp.gp.genome import Genome, GenomeArchive from pyshgp.gp.individual import Individual def load_genome(path: str) -> Genome: individual = Individual.load(path) return individual.genome def __subgenome(genome: Genome, subgenome_length: int) -> Genome: genome_length = len(genome) start = np.random.randint(0, genome_length-subgenome_length) return genome[start:start+subgenome_length] def random_subgenome(genome: Genome, min_length: int = 1, max_length: int = 5) -> Genome: subgenome_length = np.random.randint(min_length, max_length+1) return __subgenome(genome, subgenome_length) def divide_subgenome_part(genome: Genome, n_part: int) -> Sequence[Genome]: length = len(genome) subgenome_length = length // n_part if subgenome_length==0: return [Genome([i]) for i in genome] subgenomes = [] count = 0 cummulative_length = 0 for i in range(0, length, subgenome_length): subgenomes.append(genome[i:i+subgenome_length]) count += 1 cummulative_length += subgenome_length if count == n_part-1: break subgenomes.append(genome[cummulative_length:]) return subgenomes def divide_subgenome_length(genome: Genome, length: int) -> Sequence[Genome]: subgenomes = [] for i in range(0, len(genome), length): subgenomes.append(genome[i:i+length]) return subgenomes def genome_archive_random( genomes: Sequence[str], size: int, min_length: int, max_length: int ): subgenomes = [] for genome_name in genomes: genome = load_genome(genome_name) while len(subgenomes) < size: subgenome = random_subgenome(genome, min_length, max_length) if subgenome not in subgenomes: subgenomes.append(subgenome) return GenomeArchive(subgenomes) def genome_archive_part( genomes: Sequence[str], n_part: int = None, n_gene: int = None ): subgenomes = [] for genome_name in genomes: genome = load_genome(genome_name) if n_part: subgenomes.extend(divide_subgenome_part(genome, n_part)) if n_gene: subgenomes.extend(divide_subgenome_length(genome, n_gene)) return GenomeArchive(subgenomes)
2,314
28.679487
89
py
ssci2022
ssci2022-main/postprocess.py
import pandas as pd import pickle as pc from pyshgp.gp.individual import Individual from pyshgp.gp.genome import GenomeArchive from sys import argv from garch import divide_subgenome_part as divide last_problem = argv[1] summary = pd.read_csv("summary.csv", header=None) summary.columns=["prob","seed","err","len"] success = summary[(summary.prob==last_problem) & (summary.err==0)] best_seed_of_last_problem = success[success.len==success.len.min()].seed.values[0] genome = Individual.load(f"{last_problem}/{best_seed_of_last_problem}.sol").genome try: with open("subprogram.arch", "rb") as f: garch = pc.load(f) garch = garch.extend(divide(genome, 5)) except FileNotFoundError: garch = GenomeArchive(divide(genome, 5)) with open("subprogram.arch", "wb") as f: pc.dump(garch, f)
812
30.269231
82
py
ssci2022
ssci2022-main/sh/kdps_r/run8r.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps_r/run6r.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps_r/run9r.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps_r/run7r.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps_r/run5r.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps_r/run4r.py
from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed)) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
551
23
59
py
ssci2022
ssci2022-main/sh/kdps/run8.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps/run4.py
from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed)) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
550
24.045455
59
py
ssci2022
ssci2022-main/sh/kdps/run5.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps/run7.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps/run6.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/sh/kdps/run9.py
from pickle import load from sys import argv from psb import program_synth as ps problem, search, npop, ngen, nproc, seed = argv[1:] with open("subprogram.arch", "rb") as f: garch = load(f) if __name__ == "__main__": est = ps(problem=problem, search=search, npop=int(npop), ngen=int(ngen), nproc=int(nproc), seed=int(seed), archive=garch, replacement_rate=0.1, adaptation_rate=0.5) est.save(f"{problem}/{seed}.sol") error = est.solution.total_error + est.test_error.sum() length = len(est.solution.genome) with open("summary.csv", "a") as f: f.write(f"{problem},{seed},{error},{length}\n")
732
25.178571
59
py
ssci2022
ssci2022-main/arm_data/record.py
import gzip import pickle import os import numpy as np from utils import get_error, isImprovedByReplacement """Record names""" error_file = "error.csv" anytime_file = "anytime.csv" """Problems, Methods, Seeds""" problems = [ # Problems and short names "median" ] problem_names = [ "MD" ] methods = [ # Methods and names "r0.1-a0.5-kdps-r" ] method_names_map = { "r0.0-a0.0": "PushGP", "r0.1-a0.0": "PushGP+EP+RRM", "r0.1-a0.5": "PushGP+EP+ARM", "r0.1-a0.5-h": "PushGP+HP+ARM", "r0.1-a0.5-kdps": "KDPS", "r0.1-a0.5-kdps-r": "KDPSR" } method_names = [method_names_map[i] for i in methods] seeds = range( # Seeds 1001, 1026 ) """Backup files""" os.system(f"cp {error_file} {error_file}.bp") os.system(f"cp {anytime_file} {anytime_file}.bp") """Table heads""" # with open(error_file, "w") as f: # write table head # f.write("Problem,Method,Seed,Period,Error,Success Rate\n") # with open(anytime_file, "w") as f: # f.write("Problem,Method,Seed,Generation,Best Error,Average Genome Length,Improvement by Replacement\n") """Table contents""" for p, problem in enumerate(problems): # data for every problem for m, method in enumerate(methods): # data for every method for seed in seeds: # data for every seed fname = problem + "-" + method + "/" + str(seed) + ".log" # log filename train_error, test_error = get_error(fname) # train, test error train_success = (train_error==0) # is train succeeded test_success = train_success and (test_error==0) # is test succeeded with open(error_file, "a") as f: # write record f.write(f"{problem_names[p]},{method_names[m]},{seed},Train,{train_error},{train_success}\n") f.write(f"{problem_names[p]},{method_names[m]},{seed},Test,{test_error},{test_success}\n") for p, problem in enumerate(problems): # data for every problem for m, method in enumerate(methods): # data for every method for seed in seeds: fname = problem + "-" + method + "/" + str(seed) + ".log" with open(fname, "r") as log_file: for line in log_file: if "GENERATION" in line: tmp = line.replace(",","|").replace(":","|").split("|") generation = tmp[4].strip() min_error = tmp[6].replace("best=", "").strip() avg_genome_length = tmp[11].replace("avg_genome_length=", "").strip() improvement_by_replace = np.nan with open(anytime_file, "a") as f: f.write(f"{problem_names[p]},{method_names[m]},{seed},{generation},{min_error},{avg_genome_length},{improvement_by_replace}\n") # for p, problem in enumerate(problems): # data for every problem # for m, method in enumerate(methods): # data for every method # for seed in seeds: # fname = problem + "-" + method + "/" + str(seed) + ".hst.gz" # with gzip.open(fname, "rb") as hst: # generation = 1 # while True: # try: # pop = pickle.load(hst) # min_error = np.min([ind.total_error for ind in pop]) # avg_genome_length = np.mean([len(ind.genome) for ind in pop]) # improvement_by_replace = np.mean([isImprovedByReplacement(ind) for ind in pop]) # with open(anytime_file, "a") as f: # f.write(f"{problem_names[p]},{method_names[m]},{seed},{generation},{min_error},{avg_genome_length},{improvement_by_replace}\n") # except EOFError: # break # generation += 1 # print(f"Finish writing {problem} {method} {seed}")
3,881
37.435644
157
py
ssci2022
ssci2022-main/arm_data/utils.py
import numpy as np def get_error(fname): """get train and test error from log file""" with open(fname, "r") as log_file: train_flag = False for line in log_file: if train_flag: train_error = float(line.strip()) train_flag = False if "Total error" in line: train_flag = True if "Test error" in line: test_error = float(line.replace("Test error:", "").strip()) return train_error, test_error def isImprovedByReplacement(individual): if individual.info: pfit = individual.info.get("pfit") ifit = individual.error_vector return np.count_nonzero(pfit) > np.count_nonzero(ifit) return False
753
29.16
75
py
skywalking
skywalking-master/test/e2e-v2/cases/browser/docker/test.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import time from selenium import webdriver as wd from selenium.webdriver.common.desired_capabilities import DesiredCapabilities as DC hub_remote_url = os.environ.get("HUB_REMOTE_URL", "http://selenium-hub:4444/wd/hub") test_url = os.environ.get("TEST_URL", "http://testui:80/") def test_screenshot(): try: driver.get(test_url) except Exception as e: print(e) try: driver = wd.Remote( command_executor=hub_remote_url, desired_capabilities=DC.CHROME) while True: test_screenshot() time.sleep(10) finally: driver.quit()
1,384
31.209302
84
py
skywalking
skywalking-master/test/e2e-v2/cases/browser/docker/provider.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import time from urllib import request from skywalking import agent, config if __name__ == '__main__': config.service_name = 'provider-py' config.logging_level = 'DEBUG' agent.start() import socketserver from http.server import BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def _send_cors_headers(self): """ sets headers required for cors """ self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "*") self.send_header("Access-Control-Allow-Headers", "*") def do_OPTIONS(self): self.send_response(200) self._send_cors_headers() self.end_headers() def do_POST(self): time.sleep(0.5) self.send_response(200) self.send_header('Content-Type', 'application/json') self._send_cors_headers() self.end_headers() self.wfile.write('{"name": "whatever"}'.encode('ascii')) PORT = 9091 Handler = SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()
2,028
33.982759
74
py
skywalking
skywalking-master/test/e2e-v2/cases/python/consumer.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import urllib.parse from urllib import request from skywalking import agent, config if __name__ == '__main__': config.service_name = 'consumer-py' config.logging_level = 'DEBUG' config.protocol = 'http' config.collector_address = 'oap:12800' agent.start() import socketserver from http.server import BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_POST(self): self.send_response(200) self.send_header('Content-Type', 'application/json; charset=utf-8') self.end_headers() data = '{"name": "whatever"}'.encode('utf8') req = request.Request('http://medium-java:9092/users') req.add_header('Content-Type', 'application/json; charset=utf-8') req.add_header('Content-Length', str(len(data))) with request.urlopen(req, data): self.wfile.write(data) req2 = request.Request("http://provider-py-kafka:9089/users") req2.add_header('Content-Type', 'application/json; charset=utf-8') req2.add_header('Content-Length', str(len(data))) with request.urlopen(req2, data): self.wfile.write(data) PORT = 9090 Handler = SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()
2,213
37.172414
79
py
skywalking
skywalking-master/test/e2e-v2/cases/python/provider-kafka.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import time from urllib import request from skywalking import agent, config if __name__ == '__main__': config.service_name = 'provider-py-kafka' config.logging_level = 'DEBUG' config.protocol = "kafka" agent.start() import socketserver from http.server import BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_POST(self): time.sleep(0.15) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write('{"name": "whatever"}'.encode('ascii')) PORT = 9089 Handler = SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()
1,605
32.458333
74
py
skywalking
skywalking-master/test/e2e-v2/cases/python/provider.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import time from urllib import request from skywalking import agent, config if __name__ == '__main__': config.service_name = 'provider-py' config.logging_level = 'DEBUG' agent.start() import socketserver from http.server import BaseHTTPRequestHandler class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def do_POST(self): time.sleep(0.5) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write('{"name": "whatever"}'.encode('ascii')) PORT = 9091 Handler = SimpleHTTPRequestHandler with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) httpd.serve_forever()
1,568
32.382979
74
py
lale
lale-master/setup.py
# Copyright 2019-2023 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os from datetime import datetime from setuptools import find_packages, setup logger = logging.getLogger(__name__) logger.addHandler(logging.StreamHandler()) try: import builtins # This trick is borrowed from scikit-learn # This is a bit (!) hackish: we are setting a global variable so that the # main lale __init__ can detect if it is being loaded by the setup # routine, to avoid attempting to import components before installation. builtins.__LALE_SETUP__ = True # type: ignore except ImportError: pass with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() on_rtd = os.environ.get("READTHEDOCS") == "True" if on_rtd: install_requires = [] else: install_requires = [ "numpy<1.24", "black>=22.1.0", "click==8.0.4", "graphviz", "hyperopt>=0.2,<=0.2.5", "jsonschema", "jsonsubschema>=0.0.6", "scikit-learn>=1.0.0,<=1.2.0", "scipy<1.11.0", "pandas<2.0.0", "packaging", "decorator", "astunparse", "typing-extensions", ] import lale # noqa: E402 # pylint:disable=wrong-import-position if "TRAVIS" in os.environ: now = datetime.now().strftime("%y%m%d%H%M") VERSION = f"{lale.__version__}-{now}" else: VERSION = lale.__version__ extras_require = { "full": [ "mystic", "xgboost<=1.5.1", "lightgbm<4.0.0", "snapml>=1.7.0rc3,<1.12.0", "liac-arff>=2.4.0", "tensorflow>=2.4.0", "smac<=0.10.0", "numba", "aif360>=0.4.0", "protobuf<=3.20.1", "torch>=1.0", "BlackBoxAuditing", "imbalanced-learn", "cvxpy>=1.0", "fairlearn", "h5py", ], "dev": ["pre-commit"], "test": [ "mystic", "joblib", "ipython<8.8.0", "jupyter", "sphinx>=5.0.0", "sphinx_rtd_theme>=0.5.2", "docutils<0.17", "m2r2", "sphinxcontrib.apidoc", "sphinxcontrib-svg2pdfconverter", "pytest", "pyspark", "func_timeout", "category-encoders", "pynisher==0.6.4", ], "fairness": [ "mystic", "liac-arff>=2.4.0", "aif360<0.6.0", "imbalanced-learn", "protobuf<=3.20.1", "BlackBoxAuditing", ], "tutorial": [ "ipython<8.8.0", "jupyter", "xgboost<=1.5.1", "imbalanced-learn", "liac-arff>=2.4.0", "aif360==0.5.0", "protobuf<=3.20.1", "BlackBoxAuditing", "typing-extensions", ], } classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Software Development", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Artificial Intelligence", ] setup( name="lale", version=VERSION, author="Guillaume Baudart, Martin Hirzel, Kiran Kate, Parikshit Ram, Avraham Shinnar", description="Library for Semi-Automated Data Science", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/IBM/lale", python_requires=">=3.6", package_data={"lale": ["py.typed"]}, packages=find_packages(), license="Apache License 2.0", classifiers=classifiers, install_requires=install_requires, extras_require=extras_require, )
4,556
27.304348
90
py
lale
lale-master/test/test_autoai_output_consumption.py
import os import re import sys import time import traceback import unittest import urllib.request from typing import Optional import joblib import pandas as pd import sklearn from sklearn.linear_model import LogisticRegression as LR from sklearn.neighbors import KNeighborsClassifier as KNN from sklearn.tree import DecisionTreeClassifier as Tree import lale.operators from lale.lib.autoai_libs import wrap_pipeline_segments assert sklearn.__version__ == "0.23.1", "This test is for scikit-learn 0.23.1." def _println_pos(message): tb = traceback.extract_stack()[-2] match = re.search(r"<ipython-input-([0-9]+)-", tb[0]) if match: pos = f"notebook cell [{match[1]}] line {tb[1]}" else: pos = f"{tb[0]}:{tb[1]}" strtime = time.strftime("%Y-%m-%d_%H-%M-%S") to_log = f"{pos}: {strtime} {message}" # if we are running in a notebook, then we also want to print to the console # (stored in sys.__stdout__) instead of just the (redirected) sys.stdout # that goes only to the notebook # This simplifies finding where the notbook ran into a problem when a test fails out_file = sys.__stdout__ if match else sys.stdout print(to_log, file=out_file) class TestAutoAIOutputConsumption(unittest.TestCase): pickled_model_path = os.path.join( os.path.dirname(__file__), "..", "lale", "datasets", "autoai", "credit_risk.pickle", ) train_csv_path = "german_credit_data_biased_training.csv" train_csv_url = "https://raw.githubusercontent.com/pmservice/wml-sample-models/master/autoai/credit-risk-prediction/data/german_credit_data_biased_training.csv" training_df = None model = None prefix_model = None refined_model = None pipeline_content: Optional[str] = None pp_pipeline: Optional[lale.operators.TrainablePipeline] = None @classmethod def setUp(cls) -> None: # pylint:disable=arguments-differ urllib.request.urlretrieve(cls.train_csv_url, cls.train_csv_path) TestAutoAIOutputConsumption.training_df = pd.read_csv( TestAutoAIOutputConsumption.train_csv_path ) def test_01_load_pickled_model(self): try: old_model = joblib.load(TestAutoAIOutputConsumption.pickled_model_path) TestAutoAIOutputConsumption.model = old_model _println_pos(f"type(model) {type(TestAutoAIOutputConsumption.model)}") _println_pos(f"model {str(TestAutoAIOutputConsumption.model)}") except Exception as e: assert False, f"Exception was thrown during model pickle: {e}" def test_02_predict_on_model(self): t_df = TestAutoAIOutputConsumption.training_df assert t_df is not None check_X = t_df.drop(["Risk"], axis=1).values x = check_X try: m = TestAutoAIOutputConsumption.model assert m is not None pred = m.predict(x) assert len(pred) == len( x ), f"Prediction has returned unexpected number of rows {len(pred)} - expected {len(x)}" except Exception as e: assert False, f"Exception was thrown during model prediction: {e}" def test_03_print_pipeline(self): lale_pipeline = TestAutoAIOutputConsumption.model assert lale_pipeline is not None wrapped_pipeline = wrap_pipeline_segments(lale_pipeline) assert wrapped_pipeline is not None TestAutoAIOutputConsumption.pipeline_content = wrapped_pipeline.pretty_print() assert isinstance(TestAutoAIOutputConsumption.pipeline_content, str) assert len(TestAutoAIOutputConsumption.pipeline_content) > 0 _println_pos( f'pretty-printed """{TestAutoAIOutputConsumption.pipeline_content}"""' ) assert ( "lale.wrap_imported_operators()" in TestAutoAIOutputConsumption.pipeline_content # pylint:disable=unsupported-membership-test ) def test_04_execute_pipeline(self): try: with open("pp_pipeline.py", "w", encoding="utf-8") as pipeline_f: assert TestAutoAIOutputConsumption.pipeline_content is not None pipeline_f.write(TestAutoAIOutputConsumption.pipeline_content) import importlib.util spec = importlib.util.spec_from_file_location( "pp_pipeline", "pp_pipeline.py" ) assert spec is not None pipeline_module = importlib.util.module_from_spec(spec) assert spec.loader is not None # the type stubs for _Loader are currently incomplete spec.loader.exec_module(pipeline_module) # type: ignore TestAutoAIOutputConsumption.pp_pipeline = pipeline_module.pipeline # type: ignore assert isinstance( TestAutoAIOutputConsumption.pp_pipeline, lale.operators.TrainablePipeline, ) except Exception as e: assert False, f"{e}" finally: try: os.remove("pp_pipeline.py") except OSError: _println_pos("Couldn't remove pp_pipeline.py file") def test_05_train_pretty_print_pipeline(self): t_df = TestAutoAIOutputConsumption.training_df assert t_df is not None train_X = t_df.drop(["Risk"], axis=1).values train_y = t_df.Risk.values ppp = TestAutoAIOutputConsumption.pp_pipeline assert ppp is not None ppp.fit(train_X, train_y) def test_06_predict_on_pretty_print_pipeline(self): t_df = TestAutoAIOutputConsumption.training_df assert t_df is not None check_X = t_df.drop(["Risk"], axis=1).values x = check_X try: ppp = TestAutoAIOutputConsumption.pp_pipeline assert ppp is not None pred = ppp.predict(x) assert len(pred) == len( x ), f"Prediction on pretty print model has returned unexpected number of rows {len(pred)} - expected {len(x)}" except Exception as e: assert ( False ), f"Exception was thrown during pretty print model prediction: {e}" def test_07_convert_model_to_lale(self): try: lale_pipeline = TestAutoAIOutputConsumption.model assert lale_pipeline is not None TestAutoAIOutputConsumption.prefix_model = ( lale_pipeline.remove_last().freeze_trainable() ) assert isinstance( TestAutoAIOutputConsumption.prefix_model, lale.operators.TrainablePipeline, ) except Exception as e: assert False, f"Exception was thrown during model prediction: {e}" def test_08_refine_model_with_lale(self): from lale import wrap_imported_operators from lale.lib.lale import Hyperopt wrap_imported_operators() try: _println_pos( f"type(prefix_model) {type(TestAutoAIOutputConsumption.prefix_model)}" ) _println_pos(f"type(LR) {type(LR)}") # This is for classifiers, regressors needs to have different operators & different scoring metrics (e.g 'r2') pm = TestAutoAIOutputConsumption.prefix_model assert pm is not None new_model = pm >> (LR | Tree | KNN) t_df = TestAutoAIOutputConsumption.training_df assert t_df is not None train_X = t_df.drop(["Risk"], axis=1).values train_y = t_df["Risk"].values # pylint:disable=unsubscriptable-object hyperopt = Hyperopt( estimator=new_model, cv=2, max_evals=3, scoring="roc_auc" ) hyperopt_pipelines = hyperopt.fit(train_X, train_y) TestAutoAIOutputConsumption.refined_model = ( hyperopt_pipelines.get_pipeline() ) except Exception as e: assert False, f"Exception was thrown during model refinery: {e}" def test_09_predict_refined_model(self): t_df = TestAutoAIOutputConsumption.training_df assert t_df is not None check_X = t_df.drop(["Risk"], axis=1).values x = check_X try: model = TestAutoAIOutputConsumption.refined_model assert model is not None pred = model.predict(x) assert len(pred) == len( x ), f"Prediction on refined model has returned unexpected number of rows {len(pred)} - expected {len(x)}" except Exception as e: assert False, f"Exception was thrown during refined model prediction: {e}"
8,718
38.631818
164
py
lale
lale-master/test/mock_custom_operators.py
# Copyright 2019-2022 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import sklearn.linear_model import lale.operators from .mock_module import CustomOrigOperator as model_to_be_wrapped class _IncreaseRowsImpl: def __init__(self, n_rows=5): self.n_rows = n_rows def transform(self, X, y=None): subset_X = X[0 : self.n_rows] output_X = np.concatenate((X, subset_X), axis=0) return output_X def transform_X_y(self, X, y): output_X = self.transform(X) if y is None: output_y = None else: subset_y = y[0 : self.n_rows] output_y = np.concatenate((y, subset_y), axis=0) return output_X, output_y _input_transform_schema_ir = { "type": "object", "required": ["X"], "additionalProperties": False, "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, }, } _output_transform_schema_ir = { "type": "array", "items": {"type": "array", "items": {"type": "number"}}, } _input_transform_X_y_schema_ir = { "type": "object", "required": ["X", "y"], "additionalProperties": False, "properties": { "X": { "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, "y": { "anyOf": [ {"enum": [None]}, {"type": "array", "items": {"type": "number"}}, ], }, }, } _output_transform_X_y_schema_ir = { "type": "array", "laleType": "tuple", "items": [ { "description": "X", "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, { "description": "y", "anyOf": [ {"enum": [None]}, {"type": "array", "items": {"type": "number"}}, ], }, ], } _hyperparam_schema_ir = { "allOf": [ { "type": "object", "additionalProperties": False, "relevantToOptimizer": [], "properties": {"n_rows": {"type": "integer", "minimum": 0, "default": 5}}, } ], } _combined_schemas_ir = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "Combined schema for expected data and hyperparameters.", "type": "object", "tags": {"pre": [], "op": ["transformer"], "post": []}, "properties": { "hyperparams": _hyperparam_schema_ir, "input_transform": _input_transform_schema_ir, "output_transform": _output_transform_schema_ir, "input_transform_X_y": _input_transform_X_y_schema_ir, "output_transform_X_y": _output_transform_X_y_schema_ir, }, } IncreaseRows = lale.operators.make_operator(_IncreaseRowsImpl, _combined_schemas_ir) class _MyLRImpl: _wrapped_model: sklearn.linear_model.LogisticRegression def __init__(self, penalty="l2", solver="liblinear", C=1.0): self.penalty = penalty self.solver = solver self.C = C def fit(self, X, y): result = _MyLRImpl(self.penalty, self.solver, self.C) result._wrapped_model = sklearn.linear_model.LogisticRegression( penalty=self.penalty, solver=self.solver, C=self.C ) result._wrapped_model.fit(X, y) return result def predict(self, X): assert hasattr(self, "_wrapped_model") return self._wrapped_model.predict(X) _input_fit_schema_lr = { "type": "object", "required": ["X", "y"], "additionalProperties": False, "properties": { "X": {"type": "array", "items": {"type": "array", "items": {"type": "number"}}}, "y": {"type": "array", "items": {"type": "number"}}, }, } _input_predict_schema_lr = { "type": "object", "required": ["X"], "additionalProperties": False, "properties": { "X": {"type": "array", "items": {"type": "array", "items": {"type": "number"}}} }, } _output_predict_schema_lr = {"type": "array", "items": {"type": "number"}} _hyperparams_ranges = { "type": "object", "additionalProperties": False, "required": ["solver", "penalty", "C"], "relevantToOptimizer": ["solver", "penalty", "C"], "properties": { "solver": { "description": "Algorithm for optimization problem.", "enum": ["newton-cg", "lbfgs", "liblinear", "sag", "saga"], "default": "liblinear", }, "penalty": { "description": "Norm used in the penalization.", "enum": ["l1", "l2"], "default": "l2", }, "C": { "description": "Inverse regularization strength. Smaller values specify " "stronger regularization.", "type": "number", "distribution": "loguniform", "minimum": 0.0, "exclusiveMinimum": True, "default": 1.0, "minimumForOptimizer": 0.03125, "maximumForOptimizer": 32768, }, }, } _hyperparams_constraints = { "allOf": [ { "description": "The newton-cg, sag, and lbfgs solvers support only l2 penalties.", "anyOf": [ { "type": "object", "properties": { "solver": {"not": {"enum": ["newton-cg", "sag", "lbfgs"]}} }, }, {"type": "object", "properties": {"penalty": {"enum": ["l2"]}}}, ], } ] } _hyperparams_schema_lr = {"allOf": [_hyperparams_ranges, _hyperparams_constraints]} _combined_schemas_lr = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "tags": {"pre": [], "op": ["estimator", "classifier"], "post": []}, "properties": { "input_fit": _input_fit_schema_lr, "input_predict": _input_predict_schema_lr, "output_predict": _output_predict_schema_lr, "hyperparams": _hyperparams_schema_lr, }, } MyLR = lale.operators.make_operator(_MyLRImpl, _combined_schemas_lr) class _CustomParamsCheckerOpImpl: def __init__(self, fit_params=None, predict_params=None): self._fit_params = fit_params self._predict_params = predict_params def fit(self, X, y=None, **kwargs): result = _CustomParamsCheckerOpImpl(kwargs, self._predict_params) return result def predict(self, X, **predict_params): self._predict_params = predict_params _input_fit_schema_cp = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "required": ["X", "y"], "additionalProperties": False, "properties": { "X": {"type": "array", "items": {"type": "array", "items": {"type": "number"}}}, "y": {"items": {"type": "array", "items": {"type": "number"}}}, }, } _input_predict_schema_cp = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "Predict using the linear model", "type": "object", "required": ["X"], "properties": { "X": { "type": "number", } }, } _output_predict_schema_cp = { "description": "Returns predicted values.", "type": "array", "items": {"type": "number"}, } _hyperparam_schema_cp = { "allOf": [ { "description": "This first sub-object lists all constructor arguments with their " "types, one at a time, omitting cross-argument constraints.", "type": "object", "additionalProperties": False, "relevantToOptimizer": [], "properties": {}, } ], } _combined_schemas_cp = { "description": "Combined schema for expected data and hyperparameters.", "type": "object", "tags": {"pre": [], "op": ["estimator"], "post": []}, "properties": { "hyperparams": _hyperparam_schema_cp, "input_fit": _input_fit_schema_cp, "input_predict": _input_predict_schema_cp, "output_predict": _output_predict_schema_cp, }, } CustomParamsCheckerOp = lale.operators.make_operator( _CustomParamsCheckerOpImpl, _combined_schemas_cp ) CustomOrigOperator = lale.operators.make_operator(model_to_be_wrapped, {}) class _OpThatWorksWithFilesImpl: def __init__(self, ngram_range): self.ngram_range = ngram_range def fit(self, X, y=None, sample_weight=None): import pandas as pd assert ( sample_weight is not None ), "This is to test that Hyperopt passes fit_params correctly." from lale.lib.sklearn import LogisticRegression, TfidfVectorizer self.pipeline = ( TfidfVectorizer(input="content", ngram_range=self.ngram_range) >> LogisticRegression() ) self._wrapped_model = self.pipeline.fit(pd.read_csv(X, header=None), y) return self def predict(self, X): assert hasattr(self, "_wrapped_model") import pandas as pd return self._wrapped_model.predict(pd.read_csv(X, header=None)) _hyperparams_ranges_OpThatWorksWithFilesImpl = { "type": "object", "additionalProperties": False, "required": ["ngram_range"], "relevantToOptimizer": ["ngram_range"], "properties": { "ngram_range": { "default": (1, 1), "anyOf": [ { "type": "array", "laleType": "tuple", "minItemsForOptimizer": 2, "maxItemsForOptimizer": 2, "items": { "type": "integer", "minimumForOptimizer": 1, "maximumForOptimizer": 3, }, "forOptimizer": False, }, {"enum": [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]}, ], }, }, } _hyperparams_schema_OpThatWorksWithFilesImpl = { "allOf": [_hyperparams_ranges_OpThatWorksWithFilesImpl] } _combined_schemas_OpThatWorksWithFilesImpl = { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "tags": {"pre": [], "op": ["estimator", "classifier"], "post": []}, "properties": { "input_fit": {}, "input_predict": {}, "output_predict": {}, "hyperparams": _hyperparams_schema_OpThatWorksWithFilesImpl, }, } OpThatWorksWithFiles = lale.operators.make_operator( _OpThatWorksWithFilesImpl, _combined_schemas_OpThatWorksWithFilesImpl )
11,118
28.571809
94
py
lale
lale-master/test/test_custom_schemas.py
# Copyright 2019 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from test import EnableSchemaValidation from test.mock_module import CustomOrigOperator, UnknownOp import numpy as np from lightgbm import LGBMClassifier as baz from sklearn.decomposition import PCA as sk_PCA from sklearn.linear_model import Lars as sk_lars from xgboost import XGBClassifier as alt_xgb import lale import lale.type_checking from lale import schemas from lale.search.lale_grid_search_cv import get_grid_search_parameter_grids class TestCustomSchema(unittest.TestCase): def setUp(self): import sklearn.decomposition from lale.lib.sklearn import PCA as lale_PCA from lale.operators import make_operator self.sk_pca = make_operator(sklearn.decomposition.PCA, schemas={}) self.ll_pca = lale_PCA self.maxDiff = None def test_override_schemas(self): with EnableSchemaValidation(): init_schemas = self.sk_pca._schemas pca_schemas = self.ll_pca._schemas custom = self.sk_pca.customize_schema(schemas=schemas.JSON(pca_schemas)) self.assertEqual(custom._schemas, pca_schemas) self.assertEqual(self.sk_pca._schemas, init_schemas) self.assertRaises(Exception, self.sk_pca.customize_schema, schemas={}) def test_override_input(self): with EnableSchemaValidation(): init_input_schema = self.sk_pca.get_schema("input_fit") pca_input = self.ll_pca.get_schema("input_fit") custom = self.sk_pca.customize_schema(input_fit=schemas.JSON(pca_input)) self.assertEqual(custom.get_schema("input_fit"), pca_input) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.sk_pca.get_schema("input_fit"), init_input_schema) self.assertRaises(Exception, self.sk_pca.customize_schema, input_fit=42) _ = self.sk_pca.customize_schema(input_foo=pca_input) def test_override_output(self): with EnableSchemaValidation(): init_output_schema = self.sk_pca.get_schema("output_transform") pca_output = self.ll_pca.get_schema("output_transform") custom = self.sk_pca.customize_schema( output_transform=schemas.JSON(pca_output) ) self.assertEqual(custom.get_schema("output_transform"), pca_output) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual( self.sk_pca.get_schema("output_transform"), init_output_schema ) self.assertRaises(Exception, self.sk_pca.customize_schema, output=42) _ = self.sk_pca.customize_schema(output_foo=pca_output) def test_override_output2(self): init_output_schema = self.sk_pca.get_schema("output_transform") pca_output = schemas.AnyOf( [ schemas.Array(schemas.Array(schemas.Float())), schemas.Array(schemas.Float()), ] ) expected = { "anyOf": [ { "type": "array", "items": {"type": "array", "items": {"type": "number"}}, }, {"type": "array", "items": {"type": "number"}}, ] } custom = self.sk_pca.customize_schema(output_transform=pca_output) self.assertEqual(custom.get_schema("output_transform"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.sk_pca.get_schema("output_transform"), init_output_schema) def test_override_bool_param_sk(self): with EnableSchemaValidation(): init = self.sk_pca.hyperparam_schema("whiten") expected = {"default": True, "type": "boolean", "description": "override"} custom = self.sk_pca.customize_schema( whiten=schemas.Bool(default=True, desc="override") ) self.assertEqual(custom.hyperparam_schema("whiten"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.sk_pca.hyperparam_schema("whiten"), init) self.assertRaises(Exception, self.sk_pca.customize_schema, whitenX=42) def test_override_bool_param_ll(self): with EnableSchemaValidation(): init = self.ll_pca.hyperparam_schema("whiten") expected = {"default": True, "type": "boolean"} custom = self.ll_pca.customize_schema(whiten=schemas.Bool(default=True)) self.assertEqual(custom.hyperparam_schema("whiten"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("whiten"), init) self.assertRaises(Exception, self.ll_pca.customize_schema, whitenX=42) def test_override_enum_param(self): with EnableSchemaValidation(): init = self.ll_pca.hyperparam_schema("svd_solver") expected = {"default": "full", "enum": ["auto", "full"]} custom = self.ll_pca.customize_schema( svd_solver=schemas.Enum(default="full", values=["auto", "full"]) ) self.assertEqual(custom.hyperparam_schema("svd_solver"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("svd_solver"), init) def test_override_float_param(self): init = self.ll_pca.hyperparam_schema("tol") expected = { "default": 0.1, "type": "number", "minimum": -10, "maximum": 10, "exclusiveMaximum": True, "exclusiveMinimum": False, } custom = self.ll_pca.customize_schema( tol=schemas.Float( default=0.1, minimum=-10, maximum=10, exclusiveMaximum=True, exclusiveMinimum=False, ) ) self.assertEqual(custom.hyperparam_schema("tol"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("tol"), init) def test_override_int_param(self): init = self.ll_pca.hyperparam_schema("iterated_power") expected = { "default": 1, "type": "integer", "minimum": -10, "maximum": 10, "exclusiveMaximum": True, "exclusiveMinimum": False, } custom = self.ll_pca.customize_schema( iterated_power=schemas.Int( default=1, minimum=-10, maximum=10, exclusiveMaximum=True, exclusiveMinimum=False, ) ) self.assertEqual(custom.hyperparam_schema("iterated_power"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("iterated_power"), init) def test_override_null_param(self): init = self.ll_pca.hyperparam_schema("n_components") expected = {"enum": [None]} custom = self.ll_pca.customize_schema(n_components=schemas.Null()) self.assertEqual(custom.hyperparam_schema("n_components"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("n_components"), init) def test_override_json_param(self): init = self.ll_pca.hyperparam_schema("tol") expected = { "description": "Tol", "type": "number", "minimum": 0.2, "default": 1.0, } custom = self.ll_pca.customize_schema(tol=schemas.JSON(expected)) self.assertEqual(custom.hyperparam_schema("tol"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("tol"), init) def test_override_any_param(self): init = self.ll_pca.hyperparam_schema("iterated_power") expected = { "anyOf": [{"type": "integer"}, {"enum": ["auto", "full"]}], "default": "auto", } custom = self.ll_pca.customize_schema( iterated_power=schemas.AnyOf( [schemas.Int(), schemas.Enum(["auto", "full"])], default="auto" ) ) self.assertEqual(custom.hyperparam_schema("iterated_power"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca.hyperparam_schema("iterated_power"), init) def test_override_array_param(self): init = self.sk_pca.hyperparam_schema("copy") expected = { "type": "array", "minItems": 1, "maxItems": 20, "items": {"type": "integer"}, } custom = self.sk_pca.customize_schema( copy=schemas.Array(minItems=1, maxItems=20, items=schemas.Int()) ) self.assertEqual(custom.hyperparam_schema("copy"), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.sk_pca.hyperparam_schema("copy"), init) def test_override_object_param(self): init = self.sk_pca.get_schema("input_fit") expected = { "type": "object", "required": ["X"], "additionalProperties": False, "properties": {"X": {"type": "array", "items": {"type": "number"}}}, } custom = self.sk_pca.customize_schema( input_fit=schemas.Object( required=["X"], additionalProperties=False, X=schemas.Array(schemas.Float()), ) ) self.assertEqual(custom.get_schema("input_fit"), expected) lale.type_checking.validate_is_schema(custom.get_schema("input_fit")) self.assertEqual(self.sk_pca.get_schema("input_fit"), init) def test_add_constraint(self): init_expected = self.sk_pca.hyperparam_schema() expected = { "allOf": [ init_expected["allOf"][0], { "anyOf": [ { "type": "object", "properties": { "n_components": { "not": {"enum": ["mle"]}, } }, }, { "type": "object", "properties": { "svd_solver": {"enum": ["full", "auto"]}, }, }, ] }, ] } custom = self.sk_pca.customize_schema( constraint=schemas.AnyOf( [ schemas.Object(n_components=schemas.Not(schemas.Enum(["mle"]))), schemas.Object(svd_solver=schemas.Enum(["full", "auto"])), ] ) ) self.assertEqual(custom.hyperparam_schema(), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.sk_pca.hyperparam_schema(), init_expected) def test_add_multiple_constraints(self): init_expected = self.sk_pca.hyperparam_schema() expected = { "allOf": [ init_expected["allOf"][0], { "anyOf": [ { "type": "object", "properties": { "n_components": { "not": {"enum": ["mle"]}, } }, }, { "type": "object", "properties": { "svd_solver": {"enum": ["full", "auto"]}, }, }, ] }, { "anyOf": [ { "type": "object", "properties": {"copy": {"enum": [False]}}, }, { "type": "object", "properties": { "whiten": {"enum": [False]}, }, }, ] }, ] } custom = self.sk_pca.customize_schema( constraint=[ schemas.AnyOf( [ schemas.Object(n_components=schemas.Not(schemas.Enum(["mle"]))), schemas.Object(svd_solver=schemas.Enum(["full", "auto"])), ] ), schemas.AnyOf( [ schemas.Object(copy=schemas.Enum([False])), schemas.Object(whiten=schemas.Enum([False])), ] ), ] ) self.assertEqual(custom.hyperparam_schema(), expected) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.sk_pca.hyperparam_schema(), init_expected) def test_override_relevant(self): init = self.ll_pca.hyperparam_schema()["allOf"][0]["relevantToOptimizer"] expected = ["svd_solver"] custom = self.ll_pca.customize_schema(relevantToOptimizer=["svd_solver"]) self.assertEqual( custom.hyperparam_schema()["allOf"][0]["relevantToOptimizer"], expected ) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual( self.ll_pca.hyperparam_schema()["allOf"][0]["relevantToOptimizer"], init ) self.assertRaises( Exception, self.sk_pca.customize_schema, relevantToOptimizer={} ) def test_override_tags(self): with EnableSchemaValidation(): init = self.ll_pca._schemas["tags"] tags = { "pre": ["~categoricals"], "op": ["estimator", "classifier", "interpretable"], "post": ["probabilities"], } custom = self.ll_pca.customize_schema(tags=tags) self.assertEqual(custom._schemas["tags"], tags) lale.type_checking.validate_is_schema(custom._schemas) self.assertEqual(self.ll_pca._schemas["tags"], init) self.assertRaises(Exception, self.sk_pca.customize_schema, tags=42) def test_wrap_imported_operators(self): old_globals = {**globals()} try: from lale.lib.autogen import Lars from lale.lib.lightgbm import LGBMClassifier from lale.lib.xgboost import XGBClassifier lale.wrap_imported_operators( exclude_classes=["sk_PCA"], wrapper_modules=["test.mock_custom_operators"], ) from lale.operators import PlannedIndividualOp op_obj = sk_PCA() self.assertIsInstance(op_obj, sk_PCA) self.assertEqual(alt_xgb._schemas, XGBClassifier._schemas) # type: ignore self.assertEqual(baz._schemas, LGBMClassifier._schemas) # type: ignore self.assertEqual(sk_lars._schemas, Lars._schemas) self.assertIsInstance(CustomOrigOperator, PlannedIndividualOp) finally: for sym, obj in old_globals.items(): globals()[sym] = obj class TestConstraintDropping(unittest.TestCase): def test_constraint_dropping(self): from lale.lib.sklearn import LogisticRegression from lale.operators import make_operator from lale.search.schema2search_space import op_to_search_space orig_schemas = LogisticRegression._schemas mod_schemas = { **orig_schemas, "properties": { **orig_schemas["properties"], "hyperparams": { "allOf": [ s if i == 0 else {**s, "forOptimizer": False} for i, s in enumerate( orig_schemas["properties"]["hyperparams"]["allOf"] ) ] }, }, } orig_space = op_to_search_space(LogisticRegression) mod_op = make_operator(LogisticRegression._impl_class(), mod_schemas) mod_space = op_to_search_space(mod_op) # dropping constraints makes the search space smaller self.assertGreater(len(str(orig_space)), len(str(mod_space))) class TestConstraintMerging(unittest.TestCase): def test_override_float_param1(self): from lale.lib.sklearn import PCA from lale.search.schema2search_space import op_to_search_space from lale.search.search_space import SearchSpaceNumber, SearchSpaceObject pca = PCA.customize_schema( relevantToOptimizer=["tol"], tol=schemas.Float( minimum=0.25, minimumForOptimizer=0, maximum=0.5, maximumForOptimizer=1.0, exclusiveMaximum=True, exclusiveMinimum=False, ), ) search = op_to_search_space(pca) assert isinstance(search, SearchSpaceObject) num_space = list(search.choices)[0][0] assert isinstance(num_space, SearchSpaceNumber) self.assertEqual(num_space.minimum, 0.25) self.assertEqual(num_space.maximum, 0.5) self.assertTrue(num_space.exclusiveMaximum) self.assertFalse(num_space.exclusiveMinimum) def test_override_float_param2(self): from lale.lib.sklearn import PCA from lale.search.schema2search_space import op_to_search_space from lale.search.search_space import SearchSpaceNumber, SearchSpaceObject pca = PCA.customize_schema( relevantToOptimizer=["tol"], tol=schemas.Float( minimum=0, minimumForOptimizer=0.25, maximum=1.5, maximumForOptimizer=1.0, exclusiveMaximumForOptimizer=False, exclusiveMinimumForOptimizer=True, ), ) search = op_to_search_space(pca) assert isinstance(search, SearchSpaceObject) num_space = list(search.choices)[0][0] assert isinstance(num_space, SearchSpaceNumber) self.assertEqual(num_space.minimum, 0.25) self.assertEqual(num_space.maximum, 1.0) self.assertFalse(num_space.exclusiveMaximum) self.assertTrue(num_space.exclusiveMinimum) def test_override_int_param1(self): from lale.lib.sklearn import PCA from lale.search.schema2search_space import op_to_search_space from lale.search.search_space import SearchSpaceNumber, SearchSpaceObject pca = PCA.customize_schema( relevantToOptimizer=["iterated_power"], iterated_power=schemas.Float( minimum=1, minimumForOptimizer=0, maximum=5, maximumForOptimizer=6, exclusiveMaximum=True, exclusiveMinimum=False, ), ) search = op_to_search_space(pca) assert isinstance(search, SearchSpaceObject) num_space = list(search.choices)[0][0] assert isinstance(num_space, SearchSpaceNumber) self.assertEqual(num_space.minimum, 1) self.assertEqual(num_space.maximum, 5) self.assertTrue(num_space.exclusiveMaximum) self.assertFalse(num_space.exclusiveMinimum) def test_override_int_param2(self): from lale.lib.sklearn import PCA from lale.search.schema2search_space import op_to_search_space from lale.search.search_space import SearchSpaceNumber, SearchSpaceObject pca = PCA.customize_schema( relevantToOptimizer=["iterated_power"], iterated_power=schemas.Float( minimum=0, minimumForOptimizer=1, maximum=6, maximumForOptimizer=5, exclusiveMaximumForOptimizer=False, exclusiveMinimumForOptimizer=True, ), ) search = op_to_search_space(pca) assert isinstance(search, SearchSpaceObject) num_space = list(search.choices)[0][0] assert isinstance(num_space, SearchSpaceNumber) self.assertEqual(num_space.minimum, 1) self.assertEqual(num_space.maximum, 5) self.assertFalse(num_space.exclusiveMaximum) self.assertTrue(num_space.exclusiveMinimum) class TestWrapUnknownOps(unittest.TestCase): expected_schema = { "allOf": [ { "type": "object", "relevantToOptimizer": [], "additionalProperties": False, "properties": { "n_neighbors": {"default": 5}, "algorithm": {"default": "auto"}, }, } ] } def test_wrap_from_class(self): from lale.operators import PlannedIndividualOp, make_operator self.assertFalse(isinstance(UnknownOp, PlannedIndividualOp)) Wrapped = make_operator(UnknownOp) self.assertTrue(isinstance(Wrapped, PlannedIndividualOp)) self.assertEqual(Wrapped.hyperparam_schema(), self.expected_schema) instance = Wrapped(n_neighbors=3) self.assertEqual(instance.hyperparams(), {"n_neighbors": 3}) def test_wrapped_from_import(self): old_globals = {**globals()} try: from lale.operators import PlannedIndividualOp self.assertFalse(isinstance(UnknownOp, PlannedIndividualOp)) lale.wrap_imported_operators() self.assertFalse(isinstance(UnknownOp, PlannedIndividualOp)) finally: for sym, obj in old_globals.items(): globals()[sym] = obj def test_wrap_from_instance(self): from sklearn.base import clone from lale.operators import TrainableIndividualOp, make_operator self.assertFalse(isinstance(UnknownOp, TrainableIndividualOp)) instance = UnknownOp(n_neighbors=3) self.assertFalse(isinstance(instance, TrainableIndividualOp)) wrapped = make_operator(instance) self.assertTrue(isinstance(wrapped, TrainableIndividualOp)) assert isinstance( wrapped, TrainableIndividualOp ) # help type checkers that don't know about assertTrue self.assertEqual(wrapped.reduced_hyperparams(), {"n_neighbors": 3}) cloned = clone(wrapped) self.assertTrue(isinstance(cloned, TrainableIndividualOp)) self.assertEqual(cloned.reduced_hyperparams(), {"n_neighbors": 3}) class TestFreeze(unittest.TestCase): def test_individual_op_freeze_trainable(self): from lale.lib.sklearn import LogisticRegression liquid = LogisticRegression(C=0.1, solver="liblinear") self.assertIn("dual", liquid.free_hyperparams()) self.assertFalse(liquid.is_frozen_trainable()) liquid_grid = get_grid_search_parameter_grids(liquid) self.assertTrue(len(liquid_grid) > 1, f"grid size {len(liquid_grid)}") frozen = liquid.freeze_trainable() self.assertEqual(len(frozen.free_hyperparams()), 0) self.assertTrue(frozen.is_frozen_trainable()) frozen_grid = get_grid_search_parameter_grids(frozen) self.assertEqual(len(frozen_grid), 1) def test_pipeline_freeze_trainable(self): from lale.lib.sklearn import PCA, LogisticRegression liquid = PCA() >> LogisticRegression() self.assertFalse(liquid.is_frozen_trainable()) liquid_grid = get_grid_search_parameter_grids(liquid) self.assertTrue(len(liquid_grid) > 1, f"grid size {len(liquid_grid)}") frozen = liquid.freeze_trainable() self.assertTrue(frozen.is_frozen_trainable()) frozen_grid = get_grid_search_parameter_grids(frozen) self.assertEqual(len(frozen_grid), 1) def test_individual_op_freeze_trained(self): from lale.lib.sklearn import KNeighborsClassifier with EnableSchemaValidation(): trainable = KNeighborsClassifier(n_neighbors=1) X = np.array([[0.0], [1.0], [2.0]]) y_old = np.array([0.0, 0.0, 1.0]) y_new = np.array([1.0, 0.0, 0.0]) liquid_old = trainable.fit(X, y_old) self.assertEqual(list(liquid_old.predict(X)), list(y_old)) liquid_new = liquid_old.fit(X, y_new) self.assertEqual(list(liquid_new.predict(X)), list(y_new)) frozen_old = trainable.fit(X, y_old).freeze_trained() self.assertFalse(liquid_old.is_frozen_trained()) self.assertTrue(frozen_old.is_frozen_trained()) self.assertEqual(list(frozen_old.predict(X)), list(y_old)) frozen_new = frozen_old.fit(X, y_new) self.assertEqual(list(frozen_new.predict(X)), list(y_old)) def test_pipeline_freeze_trained(self): from lale.lib.sklearn import LogisticRegression, MinMaxScaler trainable = MinMaxScaler() >> LogisticRegression() X = [[0.0], [1.0], [2.0]] y = [0.0, 0.0, 1.0] liquid = trainable.fit(X, y) frozen = liquid.freeze_trained() self.assertFalse(liquid.is_frozen_trained()) self.assertTrue(frozen.is_frozen_trained()) def test_trained_individual_op_freeze_trainable(self): from lale.lib.sklearn import KNeighborsClassifier from lale.operators import TrainedIndividualOp with EnableSchemaValidation(): trainable = KNeighborsClassifier(n_neighbors=1) X = np.array([[0.0], [1.0], [2.0]]) y_old = np.array([0.0, 0.0, 1.0]) liquid = trainable.fit(X, y_old) self.assertIsInstance(liquid, TrainedIndividualOp) self.assertFalse(liquid.is_frozen_trainable()) self.assertIn("algorithm", liquid.free_hyperparams()) frozen = liquid.freeze_trainable() self.assertIsInstance(frozen, TrainedIndividualOp) self.assertTrue(frozen.is_frozen_trainable()) self.assertFalse(frozen.is_frozen_trained()) self.assertEqual(len(frozen.free_hyperparams()), 0) def test_trained_pipeline_freeze_trainable(self): from lale.lib.sklearn import LogisticRegression, MinMaxScaler from lale.operators import TrainedPipeline trainable = MinMaxScaler() >> LogisticRegression() X = [[0.0], [1.0], [2.0]] y = [0.0, 0.0, 1.0] liquid = trainable.fit(X, y) self.assertIsInstance(liquid, TrainedPipeline) self.assertFalse(liquid.is_frozen_trainable()) frozen = liquid.freeze_trainable() self.assertFalse(liquid.is_frozen_trainable()) self.assertTrue(frozen.is_frozen_trainable()) self.assertIsInstance(frozen, TrainedPipeline)
27,885
40.435364
88
py
lale
lale-master/test/test_relational_from_sklearn_manual.py
# Copyright 2021-2023 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from test.test_relational_sklearn import ( _check_trained_min_max_scaler, _check_trained_one_hot_encoder, _check_trained_ordinal_encoder, _check_trained_select_k_best, _check_trained_simple_imputer, _check_trained_standard_scaler, _check_trained_target_encoder, ) import jsonschema import numpy as np import pandas as pd import sklearn from category_encoders import TargetEncoder as SkTargetEncoder from sklearn.datasets import fetch_openml, load_digits from sklearn.feature_selection import SelectKBest as SkSelectKBest from sklearn.impute import SimpleImputer as SkSimpleImputer from sklearn.preprocessing import MinMaxScaler as SkMinMaxScaler from sklearn.preprocessing import OneHotEncoder as SkOneHotEncoder from sklearn.preprocessing import OrdinalEncoder as SkOrdinalEncoder from sklearn.preprocessing import StandardScaler as SkStandardScaler from lale.helpers import _ensure_pandas from lale.lib.rasl import Convert from lale.lib.rasl import MinMaxScaler as RaslMinMaxScaler from lale.lib.rasl import OneHotEncoder as RaslOneHotEncoder from lale.lib.rasl import OrdinalEncoder as RaslOrdinalEncoder from lale.lib.rasl import SelectKBest as RaslSelectKBest from lale.lib.rasl import SimpleImputer as RaslSimpleImputer from lale.lib.rasl import StandardScaler as RaslStandardScaler from lale.lib.rasl import TargetEncoder as RaslTargetEncoder assert sklearn.__version__ >= "1.0", sklearn.__version__ def _check_data(self, sk_data, rasl_data, msg): rasl_data = _ensure_pandas(rasl_data) self.assertEqual(sk_data.shape, rasl_data.shape, msg) for row_idx in range(sk_data.shape[0]): for col_idx in range(sk_data.shape[1]): if isinstance(sk_data, np.ndarray): sk_val = sk_data[row_idx, col_idx] else: sk_val = sk_data.iloc[row_idx, col_idx] rasl_val = rasl_data.iloc[row_idx, col_idx] if isinstance(sk_val, np.number) and np.isnan(sk_val): self.assertTrue(np.isnan(rasl_val)) else: self.assertAlmostEqual(sk_val, rasl_val, msg=(row_idx, col_idx, msg)) class TestMinMaxScaler(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = ["pandas", "spark"] def test1(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.MinMaxScaler.html >>> from sklearn.preprocessing import MinMaxScaler >>> data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]] >>> scaler = MinMaxScaler() >>> print(scaler.fit(data)) MinMaxScaler() >>> print(scaler.data_max_) [ 1. 18.] >>> print(scaler.transform(data)) [[0. 0. ] [0.25 0.25] [0.5 0.5 ] [1. 1. ]] >>> print(scaler.transform([[2, 2]])) [[1.5 0. ]] """ data = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]] sk_scaler = SkMinMaxScaler() sk_scaler.fit(data) sk_transformed_data = sk_scaler.transform(data) X = [[2, 2]] sk_transformed_X = sk_scaler.transform(X) for target in self.targets: data = Convert(astype=target).transform(data) rasl_scaler = RaslMinMaxScaler() rasl_scaler.fit(data) _check_trained_min_max_scaler(self, sk_scaler, rasl_scaler, target) rasl_transformed_data = rasl_scaler.transform(data) _check_data(self, sk_transformed_data, rasl_transformed_data, target) X = Convert(astype=target).transform(X) rasl_transformed_X = rasl_scaler.transform(X) _check_data(self, sk_transformed_X, rasl_transformed_X, target) class TestOrdinalEncoder(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = ["pandas", "spark"] def test_1(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OrdinalEncoder.html >>> from sklearn.preprocessing import OrdinalEncoder >>> enc = OrdinalEncoder() >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) OrdinalEncoder() >>> enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> enc.transform([['Female', 3], ['Male', 1]]) array([[0., 2.], [1., 0.]]) """ sk_enc = SkOrdinalEncoder() X = [["Male", 1], ["Female", 3], ["Female", 2]] sk_enc.fit(X) data = [["Female", 3], ["Male", 1]] sk_transformed = sk_enc.transform(data) for target in self.targets: rasl_enc = RaslOrdinalEncoder() X = Convert(astype=target).transform(X) rasl_enc.fit(X) data = Convert(astype=target).transform(data) rasl_transformed = rasl_enc.transform(data) _check_trained_ordinal_encoder(self, sk_enc, rasl_enc, target) _check_data(self, sk_transformed, rasl_transformed, target) def test_2(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OrdinalEncoder.html >>> import numpy as np >>> X = [['Male', 1], ['Female', 3], ['Female', np.nan]] >>> enc.fit_transform(X) array([[ 1., 0.], [ 0., 1.], [ 0., nan]]) """ sk_enc = SkOrdinalEncoder() X = [["Male", 1], ["Female", 3], ["Female", np.nan]] sk_transformed = sk_enc.fit_transform(X) for target in self.targets: rasl_enc = RaslOrdinalEncoder() X = Convert(astype=target).transform(X) rasl_transformed = rasl_enc.fit_transform(X) _check_trained_ordinal_encoder(self, sk_enc, rasl_enc, target) if target == "spark": continue # XXX issue with NaN _check_data(self, sk_transformed, rasl_transformed, target) def test_3(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OrdinalEncoder.html >>> enc.set_params(encoded_missing_value=-1).fit_transform(X) array([[ 1., 0.], [ 0., 1.], [ 0., -1.]]) """ pass # XXX encoded_missing_value is not implemented class TestSelectKBest(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = [ "pandas", "spark", ] def test1(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.feature_selection.SelectKBest.html >>> from sklearn.datasets import load_digits >>> from sklearn.feature_selection import SelectKBest, chi2 >>> X, y = load_digits(return_X_y=True) >>> X.shape (1797, 64) >>> X_new = SelectKBest(chi2, k=20).fit_transform(X, y) >>> X_new.shape (1797, 20) """ X, y = load_digits(return_X_y=True, as_frame=True) sk_selectkbest = SkSelectKBest(k=20) sk_X_new = sk_selectkbest.fit_transform( X, y ) # XXX chi2 is not supported in RASL for target in self.targets: X = Convert(astype=target).transform(X) y = Convert(astype=target).transform(y) rasl_selectkbest = RaslSelectKBest(k=20) rasl_X_new = rasl_selectkbest.fit_transform(X, y) _check_trained_select_k_best(self, sk_selectkbest, rasl_selectkbest, target) _check_data(self, sk_X_new, rasl_X_new, target) class TestOneHotEncoder(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = ["pandas", "spark"] def test_1(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OneHotEncoder.html >>> enc = OneHotEncoder(handle_unknown='ignore') >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) OneHotEncoder(handle_unknown='ignore') >>> enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> enc.transform([['Female', 1], ['Male', 4]]).toarray() array([[1., 0., 1., 0., 0.], [0., 1., 0., 0., 0.]]) >>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]]) array([['Male', 1], [None, 2]], dtype=object) >>> enc.get_feature_names_out(['gender', 'group']) array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'], ...) """ sk_enc = SkOneHotEncoder(handle_unknown="ignore") X = [["Male", 1], ["Female", 3], ["Female", 2]] sk_enc.fit(X) data = [["Female", 1], ["Male", 4]] sk_transformed_data = sk_enc.transform(data).toarray() # enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]]) for target in self.targets: X = Convert(astype=target).transform(X) data = Convert(astype=target).transform(data) rasl_enc = RaslOneHotEncoder(handle_unknown="ignore") rasl_enc.fit(X) rasl_transformed_data = rasl_enc.transform(data) _check_trained_one_hot_encoder(self, sk_enc, rasl_enc, target) _check_data(self, sk_transformed_data, rasl_transformed_data, target) # for i in range(len(sk_transformed_data)): # for j in range(len(sk_transformed_data[i])): # self.assertEqual(sk_transformed_data[i][j], rasl_transformed_data[i][j]) def test_2(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OneHotEncoder.html >>> drop_enc = OneHotEncoder(drop='first').fit(X) >>> drop_enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 0., 0.], [1., 1., 0.]]) """ pass # XXX `drop='first'` is not supported def test_3(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OneHotEncoder.html >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X) >>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 1., 0., 0.], [1., 0., 1., 0.]]) """ pass # XXX `drop='if_binary'` is not supported def test_4(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.OneHotEncoder.html >>> import numpy as np >>> X = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object).T >>> ohe = OneHotEncoder(max_categories=3, sparse=False).fit(X) >>> ohe.infrequent_categories_ [array(['a', 'd'], dtype=object)] >>> ohe.transform([["a"], ["b"]]) array([[0., 0., 1.], [1., 0., 0.]]) """ pass # XXX `max_categories=3` is not supported class TestSimpleImputer(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = ["pandas", "spark"] def test_1(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.impute.SimpleImputer.html >>> import numpy as np >>> from sklearn.impute import SimpleImputer >>> imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean') >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]]) SimpleImputer() >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]] >>> print(imp_mean.transform(X)) [[ 7. 2. 3. ] [ 4. 3.5 6. ] [10. 3.5 9. ]] """ sk_imp_mean = SkSimpleImputer(missing_values=np.nan, strategy="mean") training = [[7, 2, 3], [4, np.nan, 6], [10, 5, 9]] sk_imp_mean.fit(training) X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]] sk_transformed = sk_imp_mean.transform(X) for target in self.targets: training = Convert(astype=target).transform(training) X = Convert(astype=target).transform(X) rasl_imp_mean = RaslSimpleImputer(missing_values=np.nan, strategy="mean") rasl_imp_mean.fit(training) rasl_transformed = rasl_imp_mean.transform(X) _check_trained_simple_imputer(self, sk_imp_mean, rasl_imp_mean, target) _check_data(self, sk_transformed, rasl_transformed, target) class TestStandardScaler(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = ["pandas", "spark"] def test_1(self): """ From https://scikit-learn.org/1.1/modules/generated/sklearn.preprocessing.StandardScaler.html >>> from sklearn.preprocessing import StandardScaler >>> data = [[0, 0], [0, 0], [1, 1], [1, 1]] >>> scaler = StandardScaler() >>> print(scaler.fit(data)) StandardScaler() >>> print(scaler.mean_) [0.5 0.5] >>> print(scaler.transform(data)) [[-1. -1.] [-1. -1.] [ 1. 1.] [ 1. 1.]] >>> print(scaler.transform([[2, 2]])) [[3. 3.]] """ data = [[0, 0], [0, 0], [1, 1], [1, 1]] sk_scaler = SkStandardScaler() sk_scaler.fit(data) sk_transformed_data = sk_scaler.transform(data) data2 = [[2, 2]] sk_transformed_data2 = sk_scaler.transform(data2) for target in self.targets: data = Convert(astype=target).transform(data) data2 = Convert(astype=target).transform(data2) rasl_scaler = RaslStandardScaler() rasl_scaler.fit(data) rasl_transformed_data = rasl_scaler.transform(data) rasl_transformed_data2 = rasl_scaler.transform(data2) _check_trained_standard_scaler(self, sk_scaler, rasl_scaler, target) _check_data(self, sk_transformed_data, rasl_transformed_data, target) _check_data(self, sk_transformed_data2, rasl_transformed_data2, target) class TestTargetEncoder(unittest.TestCase): @classmethod def setUpClass(cls): cls.targets = ["pandas"] # cls.targets = ["pandas", "spark"] def test_1(self): """ From https://contrib.scikit-learn.org/category_encoders/targetencoder.html >>> from category_encoders import * >>> import pandas as pd >>> from sklearn.datasets import fetch_openml >>> display_cols = ["Id", "MSSubClass", "MSZoning", "LotFrontage", "YearBuilt", "Heating", "CentralAir"] >>> bunch = fetch_openml(name="house_prices", as_frame=True) >>> y = bunch.target > 200000 >>> X = pd.DataFrame(bunch.data, columns=bunch.feature_names)[display_cols] >>> enc = TargetEncoder(cols=['CentralAir', 'Heating'], min_samples_leaf=20, smoothing=10).fit(X, y) >>> numeric_dataset = enc.transform(X) """ display_cols = [ "Id", "MSSubClass", "MSZoning", "LotFrontage", "YearBuilt", "Heating", "CentralAir", ] bunch = fetch_openml(name="house_prices", as_frame=True) y = bunch.target > 200000 X = pd.DataFrame(bunch.data, columns=bunch.feature_names)[display_cols] sk_enc = SkTargetEncoder( cols=["CentralAir", "Heating"], min_samples_leaf=20, smoothing=10 ).fit(X, y) sk_transformed = sk_enc.transform(X) classes = sorted(list(y.unique())) for target in self.targets: rasl_enc = RaslTargetEncoder( cols=["CentralAir", "Heating"], min_samples_leaf=20, smoothing=10, classes=classes, ).fit(X, y) X2 = Convert(astype=target).transform(X) rasl_transformed = rasl_enc.transform(X2) _check_trained_target_encoder(self, sk_enc, rasl_enc.impl, target) _check_data(self, sk_transformed, rasl_transformed, target) def test_2(self): """ >>> from category_encoders.datasets import load_compass >>> X, y = load_compass() >>> hierarchical_map = {'compass': {'N': ('N', 'NE'), 'S': ('S', 'SE'), 'W': 'W'}} >>> enc = TargetEncoder(verbose=1, smoothing=2, min_samples_leaf=2, hierarchy=hierarchical_map, cols=['compass']).fit(X.loc[:,['compass']], y) >>> hierarchy_dataset = enc.transform(X.loc[:,['compass']]) >>> print(hierarchy_dataset['compass'].values) [0.62263617 0.62263617 0.90382995 0.90382995 0.90382995 0.17660024 0.17660024 0.46051953 0.46051953 0.46051953 0.46051953 0.40332791 0.40332791 0.40332791 0.40332791 0.40332791] >>> X, y = load_postcodes('binary') >>> cols = ['postcode'] >>> HIER_cols = ['HIER_postcode_1','HIER_postcode_2','HIER_postcode_3','HIER_postcode_4'] >>> enc = TargetEncoder(verbose=1, smoothing=2, min_samples_leaf=2, hierarchy=X[HIER_cols], cols=['postcode']).fit(X['postcode'], y) >>> hierarchy_dataset = enc.transform(X['postcode']) >>> print(hierarchy_dataset.loc[0:10, 'postcode'].values) [0.75063473 0.90208756 0.88328833 0.77041254 0.68891504 0.85012847 0.76772574 0.88742357 0.7933824 0.63776756 0.9019973 ] """ hierarchical_map = {"compass": {"N": ("N", "NE"), "S": ("S", "SE"), "W": "W"}} # TODO: turn this into a real test if/when hierarchy implemented with self.assertRaises(jsonschema.ValidationError): _ = RaslTargetEncoder( verbose=1, smoothing=2, min_samples_leaf=2, hierarchy=hierarchical_map, cols=["compass"], )
18,521
40.716216
150
py
lale
lale-master/test/test_lale_lib_versions.py
# Copyright 2019 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from test import EnableSchemaValidation import jsonschema import numpy as np import sklearn import sklearn.datasets import sklearn.metrics import sklearn.model_selection import xgboost from lale.lib.lale import Hyperopt from lale.lib.sklearn import ( SVC, DecisionTreeClassifier, DecisionTreeRegressor, ExtraTreesClassifier, ExtraTreesRegressor, FeatureAgglomeration, FunctionTransformer, GradientBoostingClassifier, GradientBoostingRegressor, LinearRegression, LogisticRegression, MLPClassifier, PolynomialFeatures, RandomForestClassifier, RandomForestRegressor, Ridge, VotingClassifier, ) from lale.lib.xgboost import XGBClassifier, XGBRegressor assert sklearn.__version__ == "0.20.3", "This test is for scikit-learn 0.20.3." assert xgboost.__version__ == "0.90", "This test is for XGBoost 0.90." class TestDecisionTreeClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = DecisionTreeClassifier() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = DecisionTreeClassifier(ccp_alpha=0.01) def test_with_hyperopt(self): planned = DecisionTreeClassifier trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestDecisionTreeRegressor(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = DecisionTreeRegressor() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = DecisionTreeRegressor(ccp_alpha=0.01) def test_with_hyperopt(self): planned = DecisionTreeRegressor trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, scoring="r2", cv=3, max_evals=3, ) _ = trained.predict(self.test_X) class TestExtraTreesClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = ExtraTreesClassifier() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_n_estimators(self): default = ExtraTreesClassifier.get_defaults()["n_estimators"] self.assertEqual(default, 10) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = ExtraTreesClassifier(ccp_alpha=0.01) def test_max_samples(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'max_samples' was unexpected" ): _ = ExtraTreesClassifier(max_samples=0.01) def test_with_hyperopt(self): planned = ExtraTreesClassifier trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestExtraTreesRegressor(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = ExtraTreesRegressor() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_n_estimators(self): default = ExtraTreesRegressor.get_defaults()["n_estimators"] self.assertEqual(default, 10) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = ExtraTreesRegressor(ccp_alpha=0.01) def test_max_samples(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'max_samples' was unexpected" ): _ = ExtraTreesRegressor(max_samples=0.01) def test_with_hyperopt(self): planned = ExtraTreesRegressor trained = planned.auto_configure( self.train_X, self.train_y, scoring="r2", optimizer=Hyperopt, cv=3, max_evals=3, ) _ = trained.predict(self.test_X) class TestFeatureAgglomeration(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = FeatureAgglomeration() >> LogisticRegression() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_with_hyperopt(self): planned = FeatureAgglomeration >> LogisticRegression trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3, verbose=True, ) _ = trained.predict(self.test_X) class TestFunctionTransformer(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = FunctionTransformer(func=np.log1p) >> LogisticRegression() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_pass_y(self): trainable = ( FunctionTransformer(func=np.log1p, pass_y=False) >> LogisticRegression() ) trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_validate(self): default = FunctionTransformer.get_defaults()["validate"] self.assertEqual(default, True) def test_with_hyperopt(self): planned = FunctionTransformer(func=np.log1p) >> LogisticRegression trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestGradientBoostingClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = GradientBoostingClassifier() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = GradientBoostingClassifier(ccp_alpha=0.01) def test_with_hyperopt(self): planned = GradientBoostingClassifier trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestGradientBoostingRegressor(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = GradientBoostingRegressor() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = GradientBoostingRegressor(ccp_alpha=0.01) def test_with_hyperopt(self): planned = GradientBoostingRegressor trained = planned.auto_configure( self.train_X, self.train_y, scoring="r2", optimizer=Hyperopt, cv=3, max_evals=3, ) _ = trained.predict(self.test_X) class TestLinearRegression(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = LinearRegression() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_with_hyperopt(self): planned = LinearRegression trained = planned.auto_configure( self.train_X, self.train_y, scoring="r2", optimizer=Hyperopt, cv=3, max_evals=3, ) _ = trained.predict(self.test_X) class TestLogisticRegression(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = LogisticRegression() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_multi_class(self): default = LogisticRegression.get_defaults()["multi_class"] self.assertEqual(default, "ovr") def test_solver(self): default = LogisticRegression.get_defaults()["solver"] self.assertEqual(default, "liblinear") def test_l1_ratio(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'l1_ratio' was unexpected" ): _ = LogisticRegression(l1_ratio=0.2) def test_with_hyperopt(self): planned = LogisticRegression trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestMLPClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = MLPClassifier() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_max_fun(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'max_fun' was unexpected" ): _ = MLPClassifier(max_fun=1000) def test_with_hyperopt(self): planned = MLPClassifier(max_iter=20) trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestPolynomialFeatures(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = PolynomialFeatures() >> LogisticRegression() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_order(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'order' was unexpected" ): _ = PolynomialFeatures(order="F") >> LogisticRegression() def test_with_hyperopt(self): planned = PolynomialFeatures >> LogisticRegression trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestRandomForestClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = RandomForestClassifier() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_n_estimators(self): default = RandomForestClassifier.get_defaults()["n_estimators"] self.assertEqual(default, 10) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = RandomForestClassifier(ccp_alpha=0.01) def test_max_samples(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'max_samples' was unexpected" ): _ = RandomForestClassifier(max_samples=0.01) def test_with_hyperopt(self): planned = RandomForestClassifier trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestRandomForestRegressor(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = RandomForestRegressor() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_n_estimators(self): default = RandomForestRegressor.get_defaults()["n_estimators"] self.assertEqual(default, 10) def test_ccp_alpha(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'ccp_alpha' was unexpected" ): _ = RandomForestRegressor(ccp_alpha=0.01) def test_max_samples(self): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'max_samples' was unexpected" ): _ = RandomForestRegressor(max_samples=0.01) def test_with_hyperopt(self): planned = RandomForestRegressor trained = planned.auto_configure( self.train_X, self.train_y, scoring="r2", optimizer=Hyperopt, cv=3, max_evals=3, ) _ = trained.predict(self.test_X) class TestRidge(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = Ridge() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_with_hyperopt(self): planned = Ridge trained = planned.auto_configure( self.train_X, self.train_y, scoring="r2", optimizer=Hyperopt, cv=3, max_evals=3, ) _ = trained.predict(self.test_X) class TestSVC(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = SVC() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_gamma(self): default = SVC.get_defaults()["gamma"] self.assertEqual(default, "auto_deprecated") def test_break_ties(self): with EnableSchemaValidation(): with self.assertRaisesRegex( jsonschema.ValidationError, "argument 'break_ties' was unexpected" ): _ = SVC(break_ties=True) def test_with_hyperopt(self): planned = SVC trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestVotingClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = VotingClassifier( estimators=[("lr", LogisticRegression()), ("dt", DecisionTreeClassifier())] ) trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_estimators(self): trainable = VotingClassifier( estimators=[ ("lr", LogisticRegression()), ("dt", DecisionTreeClassifier()), ("na", None), ] ) trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_with_hyperopt(self): planned = VotingClassifier( estimators=[("lr", LogisticRegression), ("dt", DecisionTreeClassifier)] ) trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestXGBClassifier(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_iris(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = XGBClassifier() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_with_hyperopt(self): planned = XGBClassifier trained = planned.auto_configure( self.train_X, self.train_y, optimizer=Hyperopt, cv=3, max_evals=3 ) _ = trained.predict(self.test_X) class TestXGBRegressor(unittest.TestCase): def setUp(self): X, y = sklearn.datasets.load_diabetes(return_X_y=True) ( self.train_X, self.test_X, self.train_y, self.test_y, ) = sklearn.model_selection.train_test_split(X, y) def test_with_defaults(self): trainable = XGBRegressor() trained = trainable.fit(self.train_X, self.train_y) _ = trained.predict(self.test_X) def test_with_hyperopt(self): planned = XGBRegressor trained = planned.auto_configure( self.train_X, self.train_y, scoring="r2", optimizer=Hyperopt, cv=3, max_evals=3, ) _ = trained.predict(self.test_X)
22,044
30.856936
87
py