Auto-format analyze.py and analyze.py

Increase default size of analyze dialog
Remove dead code
Improve comments
This commit is contained in:
David Vierra 2015-05-13 01:32:07 -10:00
parent 6d0e89f821
commit d67f115a5c
3 changed files with 67 additions and 79 deletions

View File

@ -5,16 +5,16 @@ from __future__ import absolute_import
from PySide import QtGui, QtCore from PySide import QtGui, QtCore
import logging import logging
import operator import operator
import numpy
import arrow import arrow
from mcedit2.util.load_ui import load_ui from mcedit2.util.load_ui import load_ui
from mcedit2.util.settings import Settings
from mcedit2.util.directories import getUserFilesDirectory from mcedit2.util.directories import getUserFilesDirectory
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class AnalyzeOutputDialog(QtGui.QDialog): class AnalyzeOutputDialog(QtGui.QDialog):
def __init__(self, editorSession, blockCount, entityCount, tileEntityCount, worldName, parent=None, *args, **kwargs): def __init__(self, editorSession, blockCount, entityCount, tileEntityCount, worldName, parent=None, *args,
**kwargs):
super(AnalyzeOutputDialog, self).__init__(parent, *args, **kwargs) super(AnalyzeOutputDialog, self).__init__(parent, *args, **kwargs)
self.editorSession = editorSession self.editorSession = editorSession
@ -27,12 +27,11 @@ class AnalyzeOutputDialog(QtGui.QDialog):
self.txtButton.clicked.connect(self.export_txt) self.txtButton.clicked.connect(self.export_txt)
self.csvButton.clicked.connect(self.export_csv) self.csvButton.clicked.connect(self.export_csv)
self.adjustSize()
self.exec_() self.exec_()
def setupTables(self, blockCount, entityCount, tileEntityCount): def setupTables(self, blockCount, entityCount, tileEntityCount):
blockTableView = self.blockOutputTableView blockTableView = self.blockOutputTableView
blockCounts = sorted([(self.editorSession.worldEditor.blocktypes[ i & 0xfff, i >> 12], blockCount[i]) blockCounts = sorted([(self.editorSession.worldEditor.blocktypes[i & 0xfff, i >> 12], blockCount[i])
for i in blockCount.nonzero()[0]]) for i in blockCount.nonzero()[0]])
self.blockArrayData = [(output[0].displayName, output[0].ID, self.blockArrayData = [(output[0].displayName, output[0].ID,
output[0].meta, output[1]) output[0].meta, output[1])
@ -40,7 +39,6 @@ class AnalyzeOutputDialog(QtGui.QDialog):
blockArrayHeaders = ['Name', 'ID', 'Data', 'Count'] blockArrayHeaders = ['Name', 'ID', 'Data', 'Count']
self.setupTable(self.blockArrayData, blockArrayHeaders, blockTableView) self.setupTable(self.blockArrayData, blockArrayHeaders, blockTableView)
entityTableView = self.entityOutputTableView entityTableView = self.entityOutputTableView
self.entityArrayData = [] self.entityArrayData = []
for c in entityCount, tileEntityCount: for c in entityCount, tileEntityCount:
@ -59,51 +57,50 @@ class AnalyzeOutputDialog(QtGui.QDialog):
tableView.resizeRowsToContents() tableView.resizeRowsToContents()
tableView.setSortingEnabled(True) tableView.setSortingEnabled(True)
# -- Exporting stuff -- # -- Exporting stuff --
def export_csv(self): def export_csv(self):
startingDir = getUserFilesDirectory() startingDir = getUserFilesDirectory()
name = self.worldName + "_" + arrow.now().format('DD_MM_YYYY_HH_mm_ss') name = self.worldName + "_" + arrow.now().format('DD_MM_YYYY_HH_mm_ss')
file = QtGui.QFileDialog.getSaveFileName(QtGui.qApp.mainWindow, result = QtGui.QFileDialog.getSaveFileName(QtGui.qApp.mainWindow,
self.tr("Export as .csv"), self.tr("Export as .csv"),
startingDir + "\\" + name, startingDir + "\\" + name,
"Comma Seperated Values (*.csv);;Semicolon Seperated Values (*.csv)") "Comma Separated Values (*.csv);;Semicolon Separated Values (*.csv)")
if file and file[0]: if result and result[0]:
""" """
Depending on your region, your OS uses ";" or "," as a seperator in .csv files. Depending on your region, your OS uses ";" or "," as a seperator in .csv files.
(Some countries write 0.5 as 0,5; so they use ; to seperate values). (Some countries write 0.5 as 0,5; so they use ; to separate values).
If the user selects Semicolon Seperated Values, we seperate with ";" instead of "," If the user selects Semicolon Separated Values, we separate with ";" instead of ","
""" """
sep = (";" if (file[1] == "Semicolon Seperated Values (*.csv)") else ",") sep = (";" if (result[1] == "Semicolon Separated Values (*.csv)") else ",")
self.writeFile(file[0], sep) self.writeFile(result[0], sep)
def export_txt(self): def export_txt(self):
startingDir = getUserFilesDirectory() startingDir = getUserFilesDirectory()
name = self.worldName + "_" + arrow.now().format('DD_MM_YYYY_HH_mm_ss') name = self.worldName + "_" + arrow.now().format('DD_MM_YYYY_HH_mm_ss')
file = QtGui.QFileDialog.getSaveFileName(QtGui.qApp.mainWindow, result = QtGui.QFileDialog.getSaveFileName(QtGui.qApp.mainWindow,
self.tr("Export as .txt"), self.tr("Export as .txt"),
startingDir + "\\" + name, startingDir + "\\" + name,
"Text File (*.txt)") "Text File (*.txt)")
if file and file[0]: if result and result[0]:
sep = "\t" sep = "\t"
self.writeFile(file[0], sep) self.writeFile(result[0], sep)
def writeFile(self, filename, sep): def writeFile(self, filename, sep):
with open(filename, 'w') as f: with open(filename, 'w') as f:
f.write("Blocks:\n") f.write("Blocks:\n")
f.write("Name" + sep + "Id" + sep + "Data" + sep + "Count\n") f.write("Name" + sep + "Id" + sep + "Data" + sep + "Count\n")
for b in self.blockArrayData: for b in self.blockArrayData:
string = b[0] + unicode(sep + str(b[1]) + sep + str(b[2]) + sep + str(b[3]) + "\n", encoding="utf-8") #xxx Unrolled loop string = b[0] + unicode(sep + str(b[1]) + sep + str(b[2]) + sep + str(b[3]) + "\n",
encoding="utf-8") # xxx Unrolled loop
f.write(string.encode('utf8')) f.write(string.encode('utf8'))
f.write("\nEntities:\n") f.write("\nEntities:\n")
f.write("Name" + sep + "Count\n") f.write("Name" + sep + "Count\n")
for e in self.entityArrayData: for e in self.entityArrayData:
string = e[0] + unicode(sep + str(e[1]) + "\n", encoding='utf-8') #xxx Unrolled loop string = e[0] + unicode(sep + str(e[1]) + "\n", encoding='utf-8') # xxx Unrolled loop
f.write(string.encode('utf8')) f.write(string.encode('utf8'))
class CustomTableModel(QtCore.QAbstractTableModel): class CustomTableModel(QtCore.QAbstractTableModel):
def __init__(self, arraydata, headerdata, parent=None, *args, **kwargs): def __init__(self, arraydata, headerdata, parent=None, *args, **kwargs):
QtCore.QAbstractTableModel.__init__(self, parent, *args, **kwargs) QtCore.QAbstractTableModel.__init__(self, parent, *args, **kwargs)
@ -140,4 +137,3 @@ class CustomTableModel(QtCore.QAbstractTableModel):

View File

@ -6,35 +6,33 @@
<rect> <rect>
<x>0</x> <x>0</x>
<y>0</y> <y>0</y>
<width>409</width> <width>622</width>
<height>193</height> <height>585</height>
</rect> </rect>
</property> </property>
<property name="windowTitle"> <property name="windowTitle">
<string>Analyze Output</string> <string>Analyze Output</string>
</property> </property>
<layout class="QVBoxLayout" name="verticalLayout" stretch="0,2"> <layout class="QVBoxLayout" name="verticalLayout" stretch="0,2,0,0,0">
<item> <item>
<widget class="QLabel"> <widget class="QLabel" name="label">
<property name="text"> <property name="text">
<string>Blocks Found:</string> <string>Blocks Found:</string>
</property> </property>
</widget> </widget>
</item> </item>
<item> <item>
<widget class="QTableView" name="blockOutputTableView"> <widget class="QTableView" name="blockOutputTableView"/>
</widget>
</item> </item>
<item> <item>
<widget class="QLabel"> <widget class="QLabel" name="label">
<property name="text"> <property name="text">
<string>Entities Found:</string> <string>Entities Found:</string>
</property> </property>
</widget> </widget>
</item> </item>
<item> <item>
<widget class="QTableView" name="entityOutputTableView"> <widget class="QTableView" name="entityOutputTableView"/>
</widget>
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_2"> <layout class="QHBoxLayout" name="horizontalLayout_2">
@ -83,7 +81,7 @@
</layout> </layout>
</widget> </widget>
<resources/> <resources/>
<connections> <connections>
<connection> <connection>
<sender>closeButton</sender> <sender>closeButton</sender>
<signal>clicked()</signal> <signal>clicked()</signal>

View File

@ -1,7 +1,7 @@
""" """
block_fill.py analyze.py
Optimized functions for mass-replacing blocks in a world. Get counts of blocks, entities, and tile entities in a selection.
""" """
from __future__ import absolute_import from __future__ import absolute_import
import logging import logging
@ -13,11 +13,12 @@ from mceditlib.operations import Operation
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class AnalyzeOperation(Operation): class AnalyzeOperation(Operation):
def __init__(self, dimension, selection): def __init__(self, dimension, selection):
""" """
Analyze all blocks in a selection. Analyze all blocks in a selection and return counts of block types, entity IDs and tile entity IDs.
Counts are returned in `self.blocks`, `self.entityCounts` and `self.tileEntityCounts`
:type dimension: WorldEditorDimension :type dimension: WorldEditorDimension
:type selection: `~.BoundingBox` :type selection: `~.BoundingBox`
@ -30,21 +31,16 @@ class AnalyzeOperation(Operation):
self.entityCounts = defaultdict(int) self.entityCounts = defaultdict(int)
self.tileEntityCounts = defaultdict(int) self.tileEntityCounts = defaultdict(int)
self.chunkCount = 0
self.skipped = 0 self.skipped = 0
self.sections = 0 self.sections = 0
log.info("Analyzing %s blocks", selection.volume) log.info("Analyzing %s blocks", selection.volume)
def done(self): def done(self):
log.info(u"Analyze: Skipped {0}/{1} sections".format(self.skipped, self.sections)) log.info(u"Analyze: Skipped {0}/{1} sections".format(self.skipped, self.sections))
#self.dimension.worldEditor.analyzeBlockOutput = self.blocks
#self.dimension.worldEditor.analyzeEntityOutput = self.entityCounts
#self.dimension.worldEditor.analyzeTileEntityOutput = self.tileEntityCounts
def operateOnChunk(self, chunk): def operateOnChunk(self, chunk):
self.chunkCount += 1
cx, cz = chunk.cx, chunk.cz cx, cz = chunk.cx, chunk.cz
for cy in chunk.bounds.sectionPositions(cx, cz): for cy in chunk.bounds.sectionPositions(cx, cz):
section = chunk.getSection(cy, create=False) section = chunk.getSection(cy, create=False)
@ -62,8 +58,6 @@ class AnalyzeOperation(Operation):
self.skipped += 1 self.skipped += 1
continue continue
blocks = numpy.array(section.Blocks[sectionMask], dtype='uint16') blocks = numpy.array(section.Blocks[sectionMask], dtype='uint16')
blocks |= (numpy.array(section.Data[sectionMask], dtype='uint16') << 12) blocks |= (numpy.array(section.Data[sectionMask], dtype='uint16') << 12)
b = numpy.bincount(blocks.ravel()) b = numpy.bincount(blocks.ravel())