def create(self, path, mode): self.files[path] = dict(st_mode=(S_IFREG | mode), st_nlink=1, st_size=0, st_ctime=time(), st_mtime=time(), st_atime=time()) name = path mode = self.files[path].get('st_mode') ctime = self.files[path].get('st_ctime') mtime = self.files[path].get('st_mtime') atime = self.files[path].get('st_atime') nlink = self.files[path].get('st_nlink') size = self.files[path].get('st_size') uid = os.getuid() gid = os.getgid() self.chown(path, uid, gid) # get free block for the new created file to save the metadata. num_array = Format.get_free_block(Format, 1) block_num = num_array[0] # set up the location in the disk inode_data = Format.set_inode(Format, name, mode, ctime, mtime, atime, nlink, uid, gid, size, block_num) disktools.write_block(block_num, inode_data) # update the free block bitmap Format.update_bit_map(Format, num_array) self.fd += 1 return self.fd
def ping(self, problemId): from format import Format format = Format(queue_code='queue', cpe_code='COMPILATION_ERROR', running_code='TESTING', ac_code='OK', wa_code='WRONG_ANSWER', rte_code='RUNTIME_ERROR') url = 'https://codeforces.com/api/contest.status?contestId={}&from=1&count=1&handle={}'.format( self.contestId, self.username) while True: self.robo.open(url) res = self.robo.response if not res.ok or res.status_code != 200: logger.error('Response error') logger.debug(res.error) res = json.loads(str(self.robo.parsed)) try: res = res['result'][0] #problem = res['problem']['name'] verdict = res.get('verdict', 'queue') passedTests = res.get('passedTestCount', 0) except: logger.error('error parsing: {}'.format(res)) yield format.parse(verdict, passedTests + 1)
def unlink(self, path): if Format.check_file_data(Format, path): self.data.pop(path) Format.clear_data_block(Format, path) self.files.pop(path) Format.clear_metadata_block(Format, path)
def get_weeks_text(self, year, month, first_weekday): texts = [] texts.append(self.month_text(year, month)) texts.append(self.week_text(first_weekday)) format = Format(self.key, self.path) texts += format.format(self.get_cal(self.get_weeks(year, month, first_weekday)), texts[-1]) return self.center(texts)
def get_data(self): form = Format() male = self.db.count_query("gender", "M") female = self.db.count_query("gender", "F") self.male = form.clean(male) self.female = form.clean(female)
def get_weeks_text(self, year, month, first_weekday): texts = [] texts.append(self.month_text(year, month)) texts.append(self.week_text(first_weekday)) format = Format(self.theme_uid, self.preference_path, self.log) texts += format.format( self.get_cal(self.get_weeks(year, month, first_weekday)), texts[-1]) return self.center(texts)
def get_weeks_text(self, year, month, first_weekday): texts = [] texts.append(self.month_text(year, month)) texts.append(self.week_text(first_weekday)) format = Format(self.key, self.path) texts += format.format( self.get_cal(self.get_weeks(year, month, first_weekday)), texts[-1]) return self.center(texts)
def get_data(self): form = Format() salary = self.db.query("salary") sales = self.db.query("sales") empid = self.db.query("empid") self.salary = form.clean(salary) self.sales = form.clean(sales) self.empid = form.clean(empid)
def __init__(self, thisData, thisConfig, thisExpName, thisDebug=True): Format.__init__(self, thisDebug) self.data = thisData self.config = thisConfig self._printToFilename = thisExpName self.debug = thisDebug self.colorMap = plt.get_cmap(self.config.getMatrixColorMap()) self.SPECIAL_SCORE = 12345 self.plotType = 'matrix_plot' self.title = self.data.getTitle() self.event = None
def __init__(self, thisConfig, thisDebug=True): self.debug = thisDebug Format.__init__(self, self.debug) self._config = thisConfig # N must be bigger than 3 otherwise the matrix will be all white. self._N = 4 self._metaValues = ['condA', 'condB', 'condC', 'condD', 'condE', 'condF'] #self._metaValues = ['condA'] self.getMaximum4ThisType = self._config.getMaximum4Type3 self.getMinimum4ThisType = self._config.getMinimum4Type3 self._ma = self.getMinimum4ThisType() self._mi = self.getMaximum4ThisType() self._data = collections.defaultdict(list) self._title = 'dummy test title for matrix data'
def __init__(self): nc.Creator.__init__(self) self.a = 0 self.b = 0 self.c = 0 self.f = Address('F', fmt = Format(number_of_decimal_places = 2)) self.fh = None self.fv = None self.fhv = False self.g_plane = Address('G', fmt = Format(number_of_decimal_places = 0)) self.g_list = [] self.i = 0 self.j = 0 self.k = 0 self.m = [] self.n = 10 self.r = 0 self.s = AddressPlusMinus('S', fmt = Format(number_of_decimal_places = 2), modal = False) self.t = None self.x = 0 self.y = 0 self.z = 500 self.u = 0 self.v = 0 self.w = 0 self.g0123_modal = False self.drill_modal = False self.prev_f = '' self.prev_g0123 = '' self.prev_drill = '' self.prev_retract = '' self.prev_z = '' self.useCrc = False self.useCrcCenterline = False self.gCRC = '' self.fmt = Format() self.absolute_flag = True self.ffmt = Format(number_of_decimal_places = 2) self.sfmt = Format(number_of_decimal_places = 1) self.arc_centre_absolute = False self.arc_centre_positive = False self.in_quadrant_splitting = False self.machine_coordinates = False self.drillExpanded = False self.can_do_helical_arcs = True self.shift_x = 0.0 self.shift_y = 0.0 self.shift_z = 0.0
def __init__(self): block = disktools.read_block(0) self.files = Format.get_files(Format) self.data = Format.get_data(Format) self.fd = 0 self.files['/'] = dict( st_mode=disktools.bytes_to_int(block[MODE_START:MODE_FINISH]), st_ctime=disktools.bytes_to_int(block[CTIME_START:CTIME_FINISH]), st_mtime=disktools.bytes_to_int(block[MTIME_START:MTIME_FINISH]), st_atime=disktools.bytes_to_int(block[ATIME_START:ATIME_FINISH]), st_nlink=disktools.bytes_to_int(block[NLINK_START:NLINK_FINISH])) uid = disktools.bytes_to_int(block[UID_START:UID_FINISH]) gid = disktools.bytes_to_int(block[GID_START:GID_FINISH]) self.chown('/', uid, gid)
def _guess_format_by_filename(filename): basename, ext = os.path.splitext(filename) ext = ext.lstrip(".") try: return Format.get_format_by_extension(ext) except NotImplementedError: raise FormatNotAvailableError
def __init__(self, thisConfig, thisDebug=True): self.debug = thisDebug Format.__init__(self, self.debug) self._config = thisConfig # N must be bigger than 3 otherwise the matrix will be all white. self._N = 4 self._metaValues = [ 'condA', 'condB', 'condC', 'condD', 'condE', 'condF' ] #self._metaValues = ['condA'] self.getMaximum4ThisType = self._config.getMaximum4Type3 self.getMinimum4ThisType = self._config.getMinimum4Type3 self._ma = self.getMinimum4ThisType() self._mi = self.getMaximum4ThisType() self._data = collections.defaultdict(list) self._title = 'dummy test title for matrix data'
def readdir(self, path, fh): length = len(path) if path == '/': # return the files which are not '/' and there is no '/' in their path return ['.', '..'] + [ x[length:] for x in self.files if (Format.check_path_name(Format, x[length:])) & (x != path) ] else: # return the files which have path == x[0:length] and the size of the x is larger then path and there is # no '/' in their path. return ['.', '..'] + [ x[length + 1:] for x in self.files if (Format.check_path_name(Format, x[length + 1:])) & (x[0:length] == path) & (x[length + 1:] != '') ]
def setLanguage(self,nfile): ext = Format.get(nfile) if ext == 0: self.lexer = CPP(self) elif ext == 1: self.lexer = CSharp(self) elif ext == 2: self.lexer = CSS(self) elif ext == 3: self.lexer = HTML(self) elif ext == 4: self.lexer = Java(self) elif ext == 5: self.lexer = JavaScript(self) elif ext == 6: self.lexer = Lua(self) elif ext == 7: self.lexer = Neko(self) elif ext == 8: self.lexer = Python(self) elif ext == 9: self.lexer = SQL(self) elif ext == 10: self.lexer = Squirrel(self) elif ext == 11: self.lexer = XML(self) elif ext == 12: self.lexer = YAML(self) else: self.lexer = Squirrel(self) self.lexer.setDefaultFont(self.font)
def __init__(self): nc.Creator.__init__(self) self.a = 0 self.b = 0 self.c = 0 self.f = Address('F', fmt = Format(number_of_decimal_places = 2)) self.fh = None self.fv = None self.fhv = False self.g_plane = Address('G', fmt = Format(number_of_decimal_places = 0)) self.g_list = [] self.i = 0 self.j = 0 self.k = 0 self.m = [] self.n = 10 self.r = 0 self.s = AddressPlusMinus('S', fmt = Format(number_of_decimal_places = 2), modal = False) self.t = None self.x = 0 self.y = 0 self.z = 500 self.g0123_modal = False self.drill_modal = False self.prev_f = '' self.prev_g0123 = '' self.prev_drill = '' self.prev_retract = '' self.prev_z = '' self.useCrc = False self.useCrcCenterline = False self.gCRC = '' self.fmt = Format() self.absolute_flag = True self.ffmt = Format(number_of_decimal_places = 2) self.sfmt = Format(number_of_decimal_places = 1) self.arc_centre_absolute = False self.arc_centre_positive = False self.in_arc_splitting = False self.machine_coordinates = False self.tool_length_compenstation_enabled = False self.gcode_is_metric = True self.machine_is_metric = False # Needed when looking at machine variables such as #5063 self.current_workplane = 1; # G54 by default.
def mkdir(self, path, mode): self.files[path] = dict(st_mode=(S_IFDIR | mode), st_nlink=2, st_size=0, st_ctime=time(), st_mtime=time(), st_atime=time()) name = path mode = self.files[path].get('st_mode') ctime = self.files[path].get('st_ctime') mtime = self.files[path].get('st_mtime') atime = self.files[path].get('st_atime') nlink = self.files[path].get('st_nlink') size = self.files[path].get('st_size') uid = os.getuid() gid = os.getgid() self.chown(path, uid, gid) # get free block for the new created file to save the metadata. num_array = Format.get_free_block(Format, 1) block_num = num_array[0] # set up the location in the disk inode_data = Format.set_inode(Format, name, mode, ctime, mtime, atime, nlink, uid, gid, size, block_num) disktools.write_block(block_num, inode_data) # update the free block bitmap Format.update_bit_map(Format, num_array) # find the parent path and add the nlink by 1. parent_path = Format.find_parent_path(Format, path) self.files[parent_path]['st_nlink'] += 1 Format.update_nlink(Format, parent_path, 1)
def runseccommands(self, command_delay, commandheader=0, done=False): for command in self.getcommands(): self.shell.send(command.strip() + '\r') time.sleep(command_delay) if commandheader: self.addtooutput(['\n' + Format.underline(command), ]) self.addtooutput(self.shell.recv(500000).split('\n')[1:]) if done: self.logout() return self.getoutput()
def __init__(self, thisPattern, thisAgmsv, thisAimsv, thisNumberOfTargets, thisNumberOfNonTargets, thisDebug=True): Format.__init__(self, thisDebug) self._pattern = thisPattern self._aimsv = thisAimsv self._agmsv = thisAgmsv self._numberOfTargets = thisNumberOfTargets self._numberOfNonTargets = thisNumberOfNonTargets self.debug = thisDebug self._agmStdDev = 0.0 self._aimStdDev = 0.0 self._agmNormStdDev = 0.0 self._aimNormStdDev = 0.0 self._singleTargetScore = False self._singleNonTargetScore = False # wasLimited can be used to display points that were limited in stdev in a # different way than other points. self._wasLimited = False
def rununseccommands(self, command_delay, commandheader=0, done=False): for command in self.commands: self.session.write(command.strip() + '\r') n, m, output = self.session.expect([self.prompt, ], command_delay) time.sleep(command_delay) if commandheader: self.addtooutput(['\n' + Format.underline(command), ]) self.addtooutput(output.split('\n')[1:]) if done: self.logout() return self.getoutput()
def file(dividend, divisor=100, theme='default'): try: svg = Format.create(dividend, divisor, theme).svg() buffer = io.BytesIO() buffer.write(svg.encode()) buffer.seek(0) return send_file(buffer, mimetype='image/svg+xml') except ValueError: logging.error("SVG creation failed.") abort(404)
def setUp(self): view = CmdView() data_vis = DataVis() validator = Validator() format = Format() pickle = Pickle() db = Database('company.db') self.con = Controller(view, data_vis, validator, format, pickle, db) view.controller_set(self.con)
def get_format_from_synonyme(synonyme): try: query = "MATCH (fs:FormatSynonyme)-[]-(f:Format) WHERE lower(fs.Name) = lower(\"" + synonyme + "\") RETURN f.Name AS format LIMIT 1" result = get_graph().cypher.execute(query) if len(result) != 0: return Format(result[0].format) return None except Exception: print traceback.format_exc() return None
def process_message(self, data): m = Format.format(data) m_type = m.get_type() body = m.get_body() cert = "123456" if self.identify(cert): if m_type == MessageType.REG: result = self.register(body) if m_type == MessageType.STRA: result = self.process_strategy(body) return result
def __init__(self, thisData, thisConfig, thisExpName, thisType='normal', thisDebug=True, thisUseMeta=False): Format.__init__(self, thisDebug) self.data = thisData self.config = thisConfig self._printToFilename = thisExpName self.type = thisType self.debug = thisDebug self.title = self.data.getTitle() self.useMeta = thisUseMeta self.plotType = "histogram_plot" self.fig = None self.event = None self.colors = None self.nrColors = None
def rmdir(self, path): # with multiple level support, need to raise ENOTEMPTY if contains any files length = len(path) flag = True for x in self.files: # if the first part is equal to path and the total length is longer than path # which mean it inside the path. if (x[0:length] == path) & (len(x) > length): flag = False if flag: self.files.pop(path) Format.clear_metadata_block(Format, path) else: raise ENOTEMPTY # find the parent path and reduce the nlink by 1. parent_path = Format.find_parent_path(Format, path) self.files[parent_path]['st_nlink'] -= 1 Format.update_nlink(Format, parent_path, -1)
def __init__(self): nc.Creator.__init__(self) self.a = 0 self.b = 0 self.c = 0 self.f = Address('F', fmt = Format(number_of_decimal_places = 2)) self.fh = None self.fv = None self.fhv = False self.g_plane = Address('G', fmt = Format(number_of_decimal_places = 0)) self.g_list = [] self.i = 0 self.j = 0 self.k = 0 self.m = [] self.n = 10 self.r = 0 self.s = AddressPlusMinus('S', fmt = Format(number_of_decimal_places = 2), modal = False) self.t = None self.x = 0 self.y = 0 self.z = 500 self.g0123_modal = False self.drill_modal = False self.prev_f = '' self.prev_g0123 = '' self.prev_drill = '' self.prev_retract = '' self.prev_z = '' self.useCrc = False self.useCrcCenterline = False self.gCRC = '' self.fmt = Format() self.absolute_flag = True self.ffmt = Format(number_of_decimal_places = 2) self.sfmt = Format(number_of_decimal_places = 1) self.arc_centre_absolute = False self.arc_centre_positive = False self.in_quadrant_splitting = False self.drillExpanded = False self.can_do_helical_arcs = True self.shift_x = 0.0 self.shift_y = 0.0 self.shift_z = 0.0
def run(self): if self.pool: self.pool.acquire() if self.tty.login(): if self.tty.os == 1:self.tty.setcommands(self.alucommands) elif self.tty.os == 2:self.tty.setcommands(self.xrcommands) elif self.tty.os == 3:self.tty.setcommands(self.ioscommands) elif self.tty.os == 4:self.tty.setcommands(self.junoscommands) elif self.tty.os == 5:self.tty.setcommands(self.asacommands) else: return output = self.tty.runcommands(self.commanddelay, commandheader=self.commandheader, done=True) else: print "Could not log in to " + self.host.strip() if self.pool: self.pool.release() return self.tty.setoutput(Format.siftoutput(output, siftout=[self.username, self.password, self.tty.prompt])) if self.pool: self.pool.release() return
def run(self): if self.pool: self.pool.acquire() if self.tty.login(): if self.tty.os == 1: commands = self.alucommands elif self.tty.os == 2: commands = self.xrcommands elif self.tty.os == 3: commands = self.ioscommands elif self.tty.os == 4: commands = self.junoscommands elif self.tty.os == 5: commands = self.asacommands else: return self.tty.setcommands(commands[0]) output = self.tty.runcommands(self.commanddelay, commandheader=self.commandheader) for command in commands[1]: if command.commanddelay: self.commanddelay = command.commanddelay self.tty.setcommands(Command_parser.generate_commands(command, output)) output = self.tty.runcommands(self.commanddelay, commandheader=self.commandheader) else: print "Could not log in to " + self.host.strip() if self.pool: self.pool.release() return output = self.tty.getoutput() self.tty.setoutput(Format.siftoutput(output, siftout=[self.username, self.password, self.tty.prompt])) if self.pool: self.pool.release() return
class Data(Format): """ Data object containing target and non target scores per test subject. """ def __init__(self, thisConfig, thisTitle, thisThreshold, thisDataType, thisDebug=True, thisSources='database'): Format.__init__(self, thisDebug) self.config = thisConfig self._title = thisTitle self._defaultThreshold = thisThreshold self._dataType = thisDataType # Annotate _doves, _phantoms, _worms and _chameleons self.debug = thisDebug self._sources = thisSources self._format = Format(self.debug) self._plotType = None # Target scores per label and meta value pattern. self._targetScores = collections.defaultdict(list) # Number of targets per label. self._targetCnt = collections.Counter() # Non target scores per label and meta value pattern. self._nonTargetScores = collections.defaultdict(list) # Number of non targets per label. self._nonTargetCnt = collections.Counter() # Target scores per label. self._targetScores4Label = collections.defaultdict(list) self._targetScores4MetaValue = collections.defaultdict(list) # Non target scores per label. self._nonTargetScores4Label = collections.defaultdict(list) self._nonTargetScores4MetaValue = collections.defaultdict(list) self._results = collections.defaultdict(list) self._results4Subject = collections.defaultdict(list) self._nrDistinctMetaDataValues = 0 # Contains: { speakerId: metaDataValue } self._metaDataValues = collections.defaultdict(set) self._LabelsToShowAlways = [] self._minimumScore = collections.defaultdict(dict) self._maximumScore = collections.defaultdict(dict) # Keep track of labels. self._targetLabels = set() self._nonTargetLabels = set() # Do we allow both scores (A vs B and B vs A) in a symmetric tests or only the first read? self._allowDups = self.config.getAllowDups() if self.debug: print('Data._source(s):') for el in self._sources: print(el) # If the user did not specify a filename, we assume a database as the source. if self._sources == 'database': print("You need to add some code for this to work!") # And remove the sys.exit(1) statement. sys.exit(1) res = self._readFromDatabase() else: res = self._readFromFiles(self._sources) # # Choose between decoder for type of results. # if self._dataType == 'type3': self._decodeType3Results(res) elif self._dataType == 'type2': print("Type2 data is not supported anymore. Convert it to type3!") sys.exit(1) elif self._dataType == 'type1': self._decodeType1Results(res) else: print("Unknown data type, must be 'type1' or 'type3'.") sys.exit(1) def getMax(self): return self._maAll def getMin(self): return self._miAll def getMetaDataValues(self): return self._metaDataValues def getDefaultThreshold(self): return self._defaultThreshold def getResults(self): return self._results def getResults4Subject(self): return self._results4Subject def getTargetScores(self): """ :return: dict of target scores. """ return self._targetScores def getTargetCnt(self): """ :return: return dict containing target counts. """ return self._targetCnt def getNonTargetScores(self): """ :return: return dict of non target scores. """ return self._nonTargetScores def getNonTargetCnt(self): """ :return: return dict containing non target counts. """ return self._nonTargetCnt def getTargetScoreValues(self): thisList = self.getTargetScores() return self._extractValues(thisList) def getNonTargetScoreValues(self): thisList = self.getNonTargetScores() return self._extractValues(thisList) def _extractValues(self, thisList): ret = [] for el in list(thisList.values()): ret += el return ret def getTargetScores4MetaValue(self, metaValue): return self._targetScores4MetaValue[metaValue] def getTargetScores4Label(self, label): return self._targetScores4Label[label] def getLabelsWithTargetScores(self): return self._targetScores4Label def getLabelsWithNonTargetScores(self): return self._nonTargetScores4Label def getLabelsAndScoresForMetaValue(self, data, metaValue): """ :param data: [{'a_#_conditionA': [('p', 2.3), ('p', -3.0), ('p', 1), ('q', 2.0), ('q', 0.1)]}, {'b_#_conditionA': [('p', 6.0), ('p', 1.0), ('q', 3.0)]}] {'a_#_conditionB': [('p', 1.0), ('p', 2.0), ('q', 1.0), ('q', -1.2)]}] :param metaValue: 'conditionA' :return: row = {'a': [('p', 2.3), ('p', -3.0), ('p', 1), ('q', 2.0), ('q', 0.1)] 'b': [('p', 6.0), ('p', 1.0), ('q', 3.0)] } ... """ row = collections.defaultdict(list) odata = collections.OrderedDict(sorted(list(data.items()), key=lambda x: x[0], reverse=True)) for pattern in list(odata.keys()): thisMetaValue = self.getMetaFromPattern(pattern) if thisMetaValue == metaValue: label = self.getLabelFromPattern(pattern) row[label] += odata[pattern] return row def getNonTargetScores4MetaValue(self, metaValue): return self._nonTargetScores4MetaValue[metaValue] def getNonTargetScores4Label(self, label): return self._nonTargetScores4Label[label] def getTargetLabels(self): return list(self._targetLabels) def getNonTargetLabels(self): """ Get non target labels from raw data input. Split target label field using the --- separator. The first part is the label, the second the name of the wav file / feature vector used in the experiment. :return: set of labels. Each label is of type str. """ return list(self._nonTargetLabels) def getNrDistinctMetaDataValues(self): return self._nrDistinctMetaDataValues def setLabelsToShowAlways(self, theseLabels): tmp = [] for label in theseLabels: tmp.append(label.strip()) self._LabelsToShowAlways = tmp def getLabelsToShowAlways(self): return self._LabelsToShowAlways def getMaximumScore(self, meta): return self._maximumScore[meta] def getMinimumScore(self, meta): return self._minimumScore[meta] def compAverageScore(self, scores): """ Compute average score from dict of scores. :param scores: dict containing list of scores for key = label :return: float: average score """ tot = sum(scores) cnt = len(scores) avg = float(tot) / float(cnt) return avg def getTitle(self): return self._title def minMax(self, score, mi, ma): """ Compute minimum and maximum value from a list of float scores. :param score: list of scores :return: minimum value and maximum value """ mi = min(score, mi) ma = max(score, ma) return mi, ma def minMax2(self, scoreDict, label, mi, ma): """ Compute minimum and maximum value from a list of scoreDicts. :param scoreDict: list of scores :param label: string :param mi: float: minimum input value :param ma: float: maximum input value :return: minimum value and maximum value """ for key in list(scoreDict.keys()): if label in key: mi = min(scoreDict[key], mi) ma = max(scoreDict[key], ma) return mi, ma def _sanitize(self, l1, f1, l2, f2, score, truth, metaValue): """ Get rid of leading and trailing spaces. :param l1: string label :param f1: floating point number as a string :param l2: string label :param f2: floating point number as a string :param score: string floating point number :param truth: boolean as a string :param metaValue: string :return: """ l1 = l1.strip() f1 = f1.strip() l2 = l2.strip() f2 = f2.strip() score = score.strip() truth = truth.strip() metaValue = metaValue.strip() return l1, f1, l2, f2, score, truth, metaValue def _decodeType3Results(self, res): """ Decoder for cross identification type results file. Example of the format used: 80374 0000000017133729a 80359 0000000016842970b 2.1088616847991943 FALSE META_VAL1 148407 0000260007968376b 89823 0000000008087650a 0.33669018745422363 FALSE META_VAL1 179408 03ea7cce-a192626a 80372 0000000016749939b 1.26323664188385 FALSE META_VAL2 80344 0000000016888750a 80344 0000000015560933b 4.423274517059326 TRUE META_VAL2 etc. :param res: list of strings (text lines) of raw data resulting from a series of trials. Type 3 data contains 7 fields: field 1: string: label identifying a subject (training data) field 2: string: name of data file containing biometric features or raw data originating from the subject denoted by field 1 used for training the test model field 3: string: label identifying a subject (test data) field 4: string: name of data file containing biometric features or raw data originating from the subject denoted by field 3 used for training the reference model field 5: string: float value: score of trial field 6: boolean: ground truth field 7: string: meta data value for the trial Field 7 can be used to contrast experiments in the zoo plot. So if you have 2 experiments where you change one variable, when doing a cross identification test, the meta value can be used to group the experiment's scores. """ totCnt = 0 resCnt = 0 # For type 3 scores we assume that the scores are (Log) Likelyhood Ratios ranging between 0 and +infinity. onlyOnce = set() revRepeatCnt = 0 selfCnt = 0 valuesCnt = collections.Counter() # Set max and min function for this type. self.getMaximum4ThisType = self.config.getMaximum4Type3 self.getMinimum4ThisType = self.config.getMinimum4Type3 # Scores are scalar float values. self._miAll = self.getMaximum4ThisType() self._maAll = self.getMinimum4ThisType() for line in res: if ',' in line: splitChar = ',' else: splitChar = None try: l1, f1, l2, f2, score, truth, metaValue = line.split(splitChar) if splitChar: l1, f1, l2, f2, score, truth, metaValue = self._sanitize(l1, f1, l2, f2, score, truth, metaValue) except Exception as e: print('Error in', line) print('Use either comma or space as separator.') print(e) else: # We want to sort the data when choosing colors. # Therefore we convert to numbers if possible # otherwise we assume string values. metaValue = convert(metaValue) # Keep track of distinct meta data values. valuesCnt[metaValue] += 1 if not metaValue in self._minimumScore: self._minimumScore[metaValue] = self.getMaximum4ThisType() self._maximumScore[metaValue] = self.getMinimum4ThisType() l1_0 = l1 + '---' + f1 l2_0 = l2 + '---' + f2 # If the score is not numerical, then we skip everything. try: score = float(score) except Exception as e: print('Error in', line) print(e) else: self._miAll = min(self._miAll, score) self._maAll = max(self._maAll, score) self._minimumScore[metaValue] = min(self._minimumScore[metaValue], score) self._maximumScore[metaValue] = max(self._maximumScore[metaValue], score) if l1_0 == l2_0: selfCnt += 1 # Selfies are not interesting and therefore skipped # continue if not (l1_0, l2_0) in onlyOnce: onlyOnce.add((l1_0, l2_0)) if not self._allowDups: # We do not want to include an experiment twice, # assuming that the scores are symmetric. # This may not be the case! if (l2_0, l1_0) in onlyOnce: revRepeatCnt += 1 continue resCnt += 1 # Keep track of labels associated with meta data values. metaValue = str(metaValue) pattern = l1 + self.LABEL_SEPARATOR + metaValue # Keep track of results for ranking purposes. # print 'adding element to results[', l1 + self.LABEL_SEPARATOR + metaValue, ']' self._results[pattern].append((l2, score)) self._results4Subject[metaValue, l1].append((l2, score)) # code is just for debugging self._metaDataValues[metaValue].add(l1) self._metaDataValues[metaValue].add(l2) totCnt += 1 if truth.lower() == 'true': self._targetScores[pattern].append(score) self._targetScores4Label[l1].append(score) self._targetScores4MetaValue[metaValue].append(score) self._targetCnt[metaValue] += 1 self._targetLabels.add(l1) else: self._nonTargetScores[pattern].append(score) self._nonTargetScores4Label[l1].append(score) self._nonTargetScores4MetaValue[metaValue].append(score) self._nonTargetCnt[metaValue] += 1 self._nonTargetLabels.add(l1) if self.debug: print('Number of results in file:', resCnt) print('Number of subjects:', len(self._results4Subject)) print('Number of scores:', totCnt) if totCnt == 0: print('No scores were found. Maybe the dataType is not set correctly.') print("DataType is '%s'" % self._dataType) print('Is this correct?') sys.exit(1) print("Number of target and non target scores for: ") maxLen = 0 for metaValue in self._nonTargetCnt: maxLen = max(maxLen, len(metaValue)) template = "{:<%d}" % maxLen scoreLen = len(str(self.compLen(self._nonTargetScores))) template += " {:>%d} {:>%d}" % (scoreLen + 1, scoreLen + 1) for metaValue in self._targetCnt: #print("{:<10} {:>7} {:>7}".format(metaValue, self._targetCnt[metaValue], self._nonTargetCnt[metaValue])) print(template.format(metaValue, self._targetCnt[metaValue], self._nonTargetCnt[metaValue])) # print("Number of non target scores for: ") print(template.format("Total", self.compLen(self._targetScores), self.compLen(self._nonTargetScores))) # print('Total number of target scores:', self.compLen(self._targetScores)) # print('Total number of non target scores:', self.compLen(self._nonTargetScores)) print('Number of repeats (multiple instances of same data in input):', revRepeatCnt) print('Number of selfies (A vs A):', selfCnt) self._nrDistinctMetaDataValues = len(self._metaDataValues) print('Nr of distinct meta data values:', self._nrDistinctMetaDataValues) def _decodeType1Results(self, res): """ This function is a stub. You need to convert the type1 data read from the database here and convert it to the type3 format. Then call _decodeType3Results(res) :param res: :return: """ ret = [] for line in res: # Do your type1 to type3 conversion here ret.append(line) # Finally call the Type3 decoder self._decodeType3Results(ret) return ret def compLen(self, scoreDict): """ Compute the total length of the values stored in scoreDict :param scoreDict: key = string: label, value = float: score :return: int: total length """ tot = 0 for k in list(scoreDict.keys()): tot += len(scoreDict[k]) return tot def _readFromDatabase(self): """ This function contains some (incomplete) example code in case you want to read data from a database. It is suggested to add some code here which does the following: 1: connect to the database 2: read the data from the database and concatenate the data elements separated by spaces so that you end up with a list of lines. 3: then exit this function 4: In _decodeType1Results transform the lines to the Type3 format and call _decodeType3Results there. :return: list of lines containing data elements separated by spaces. """ conn = sqlite3.connect('database.sqlite') c = conn.cursor() res = c.execute("SELECT ProbeId, GalleryId, Score FROM crossidentificationresults") # Note: ProbeId = label1 corresponding to a test model # GalleryId = label2 corresponding to a training model # Score = distance measure / score between label1 and label2 return res def _readFromFiles(self, filenames): """ Read raw lines of text from a text file. Strip lines of CR/LF :param filename: string: name of file containing text :return: list of strings """ def readFromFile(filename): try: f = open(filename, 'r') lines = f.readlines() f.close() res = [] for line in lines: res.append(line.strip()) return res except IOError as e: print(e) sys.exit(1) ret = [] for filename in filenames: print("Reading data from: {}".format(filename)) ret = ret + readFromFile(filename) return ret def writeScores2file(self, scoreDict, expName, extention): """ Write scores to a file :param scoreDict: dict of scores, key = label :param expName: string used as part of the file name :param extention: string used as file extention :return: not a thing """ dataOutputPath = self.config.getOutputPath() k = list(scoreDict.keys()) try: if not path.exists(dataOutputPath): makedirs(dataOutputPath) except Exception as e: print('writeScores2file', e) sys.exit(1) scoresPerMetaValue = collections.defaultdict(list) for el in k: scores = scoreDict[el] metaValue = self._format.getMetaFromPattern(el) scoresPerMetaValue[metaValue].append(scores) for metaValue in scoresPerMetaValue: scores = scoresPerMetaValue[metaValue] filename = dataOutputPath + path.sep + expName + '_' + metaValue + extention # We do not like spaces in file names. # Sorry windows dudes and dudettes ! filename = singleSanitize(filename) if self.config.getAllwaysSave(): background = AsyncWrite(filename, scores, self.debug) background.start() background.join() else: if not path.exists(filename): background = AsyncWrite(filename, scores, self.debug) background.start() background.join() else: print("File %s already exists." % filename)
pass # #try: # from xml_format import XmlFormat # available_formats.append(XmlFormat) #except ImportError: # pass try: from yaml_format import YamlFormat available_formats.append(YamlFormat) except ImportError: pass Format.register_formats(available_formats) class FormatNotAvailableError(Exception): pass def loads(data_st, format): if format not in available_formats: raise FormatNotAvailableError else: return format.loads(data_st) def dumps(data, format): if format not in available_formats: raise FormatNotAvailableError else:
# -*- coding: utf-8 -*- """ Created on Wed Jan 15 16:50:54 2020 @author: YWu """ from format import Format if __name__ == '__main__': pts = 49 cols = [0, 5, 6, 8] rows = [12, 55] tool = '930' film = 'w' fmt = Format() fmt.create_format(tool, film, pts, cols, rows) #fmt.del_format(tool, film)
class Creator(nc.Creator): def __init__(self): nc.Creator.__init__(self) self.a = 0 self.b = 0 self.c = 0 self.f = Address('F', fmt = Format(number_of_decimal_places = 2)) self.fh = None self.fv = None self.fhv = False self.g_plane = Address('G', fmt = Format(number_of_decimal_places = 0)) self.g_list = [] self.i = 0 self.j = 0 self.k = 0 self.m = [] self.n = 10 self.r = 0 self.s = AddressPlusMinus('S', fmt = Format(number_of_decimal_places = 2), modal = False) self.t = None self.x = 0 self.y = 0 self.z = 500 self.g0123_modal = False self.drill_modal = False self.prev_f = '' self.prev_g0123 = '' self.prev_drill = '' self.prev_retract = '' self.prev_z = '' self.useCrc = False self.useCrcCenterline = False self.gCRC = '' self.fmt = Format() self.absolute_flag = True self.ffmt = Format(number_of_decimal_places = 2) self.sfmt = Format(number_of_decimal_places = 1) self.arc_centre_absolute = False self.arc_centre_positive = False self.in_quadrant_splitting = False self.machine_coordinates = False self.drillExpanded = False self.can_do_helical_arcs = True self.shift_x = 0.0 self.shift_y = 0.0 self.shift_z = 0.0 ############################################################################ ## Codes def SPACE(self): return('') def FORMAT_FEEDRATE(self): return('%.2f') def FORMAT_ANG(self): return('%.1f') def FORMAT_TIME(self): return('%.2f') def FORMAT_DWELL(self): return('P%f') def BLOCK(self): return('N%i') def COMMENT(self,comment): return( ('(%s)' % comment ) ) def VARIABLE(self): return( '#%i') def VARIABLE_SET(self): return( '=%.3f') def PROGRAM(self): return( 'O%i') def PROGRAM_END(self): return( 'M02') def SUBPROG_CALL(self): return( 'M98' + self.SPACE() + 'P%i') def SUBPROG_END(self): return( 'M99') def STOP_OPTIONAL(self): return('M01') def STOP(self): return('M00') def IMPERIAL(self): return('G20') def METRIC(self): return('G21') def ABSOLUTE(self): return('G90') def INCREMENTAL(self): return('G91') def SET_TEMPORARY_COORDINATE_SYSTEM(self): return('G92') def REMOVE_TEMPORARY_COORDINATE_SYSTEM(self): return('G92.1') def POLAR_ON(self): return('G16') def POLAR_OFF(self): return('G15') def PLANE_XY(self): return('17') def PLANE_XZ(self): return('18') def PLANE_YZ(self): return('19') def TOOL(self): return('T%i' + self.SPACE() + 'M06') def TOOL_DEFINITION(self): return('G10' + self.SPACE() + 'L1') def WORKPLANE(self): return('G%i') def WORKPLANE_BASE(self): return(53) def SPINDLE_CW(self): return('M03') def SPINDLE_CCW(self): return('M04') def COOLANT_OFF(self): return('M09') def COOLANT_MIST(self): return('M07') def COOLANT_FLOOD(self): return('M08') def GEAR_OFF(self): return('?') def GEAR(self): return('M%i') def GEAR_BASE(self): return(37) def RAPID(self): return('G00') def FEED(self): return('G01') def ARC_CW(self): return('G02') def ARC_CCW(self): return('G03') def DWELL(self): return('G04') def DRILL(self): return('G81') def DRILL_WITH_DWELL(self, format, dwell): return('G82' + self.SPACE() + (format.string(dwell))) def PECK_DRILL(self): return('G83') def PECK_DEPTH(self, format, depth): return(self.SPACE() + 'Q' + (format.string(depth))) def RETRACT(self, format, height): return(self.SPACE() + 'R' + (format.string(height))) def END_CANNED_CYCLE(self): return('G80') def TAP(self): return('G84') def TAP_DEPTH(self, format, depth): return(self.SPACE() + 'K' + (format.string(depth))) def X(self): return('X') def Y(self): return('Y') def Z(self): return('Z') def A(self): return('A') def B(self): return('B') def C(self): return('C') def CENTRE_X(self): return('I') def CENTRE_Y(self): return('J') def CENTRE_Z(self): return('K') def RADIUS(self): return('R') def TIME(self): return('P') def PROBE_TOWARDS_WITH_SIGNAL(self): return('G38.2') def PROBE_TOWARDS_WITHOUT_SIGNAL(self): return('G38.3') def PROBE_AWAY_WITH_SIGNAL(self): return('G38.4') def PROBE_AWAY_WITHOUT_SIGNAL(self): return('G38.5') def MACHINE_COORDINATES(self): return('G53') def EXACT_PATH_MODE(self): return('G61') def EXACT_STOP_MODE(self): return('G61.1') ############################################################################ ## Internals def write_feedrate(self): self.f.write(self) def write_preps(self): self.g_plane.write(self) for g in self.g_list: self.write(self.SPACE() + g) self.g_list = [] def write_misc(self): if (len(self.m)) : self.write(self.m.pop()) def write_blocknum(self): self.write(self.BLOCK() % self.n) self.n += 10 def write_spindle(self): self.s.write(self) ############################################################################ ## Programs def program_begin(self, id, name=''): self.write((self.PROGRAM() % id) + self.SPACE() + (self.COMMENT(name))) self.write('\n') def program_stop(self, optional=False): self.write_blocknum() if (optional) : self.write(self.SPACE() + self.STOP_OPTIONAL() + '\n') self.prev_g0123 = '' else : self.write(self.STOP() + '\n') self.prev_g0123 = '' def program_end(self): self.write_blocknum() self.write(self.SPACE() + self.PROGRAM_END() + '\n') def flush_nc(self): if len(self.g_list) == 0 and len(self.m) == 0: return self.write_blocknum() self.write_preps() self.write_misc() self.write('\n') ############################################################################ ## Subprograms def sub_begin(self, id, name=''): self.write((self.PROGRAM() % id) + self.SPACE() + (self.COMMENT(name))) self.write('\n') def sub_call(self, id): self.write_blocknum() self.write(self.SPACE() + (self.SUBPROG_CALL() % id) + '\n') def sub_end(self): self.write_blocknum() self.write(self.SPACE() + self.SUBPROG_END() + '\n') ############################################################################ ## Settings def imperial(self): self.g_list.append(self.IMPERIAL()) self.fmt.number_of_decimal_places = 4 def metric(self): self.g_list.append(self.METRIC()) self.fmt.number_of_decimal_places = 3 def absolute(self): self.g_list.append(self.ABSOLUTE()) self.absolute_flag = True def incremental(self): self.g_list.append(self.INCREMENTAL()) self.absolute_flag = False def polar(self, on=True): if (on) : self.g_list.append(self.POLAR_ON()) else : self.g_list.append(self.POLAR_OFF()) def set_plane(self, plane): if (plane == 0) : self.g_plane.set(self.PLANE_XY()) elif (plane == 1) : self.g_plane.set(self.PLANE_XZ()) elif (plane == 2) : self.g_plane.set(self.PLANE_YZ()) def set_temporary_origin(self, x=None, y=None, z=None, a=None, b=None, c=None): self.write_blocknum() self.write(self.SPACE() + (self.SET_TEMPORARY_COORDINATE_SYSTEM())) if (x != None): self.write( self.SPACE() + 'X ' + (self.fmt.string(x + self.shift_x)) ) if (y != None): self.write( self.SPACE() + 'Y ' + (self.fmt.string(y + self.shift_y)) ) if (z != None): self.write( self.SPACE() + 'Z ' + (self.fmt.string(z + self.shift_z)) ) if (a != None): self.write( self.SPACE() + 'A ' + (self.fmt.string(a)) ) if (b != None): self.write( self.SPACE() + 'B ' + (self.fmt.string(b)) ) if (c != None): self.write( self.SPACE() + 'C ' + (self.fmt.string(c)) ) self.write('\n') def remove_temporary_origin(self): self.write_blocknum() self.write(self.SPACE() + (self.REMOVE_TEMPORARY_COORDINATE_SYSTEM())) self.write('\n') ############################################################################ ## new graphics origin- make a new coordinate system and snap it onto the geometry ## the toolpath generated should be translated def translate(self,x=None, y=None, z=None): self.shift_x = -x self.shift_y = -y self.shift_z = -z ############################################################################ ## Tools def tool_change(self, id): self.write_blocknum() self.write(self.SPACE() + (self.TOOL() % id) + '\n') self.t = id def tool_defn(self, id, name='', radius=None, length=None, gradient=None): self.write_blocknum() self.write(self.SPACE() + self.TOOL_DEFINITION()) self.write(self.SPACE() + ('P%i' % id) + ' ') if (radius != None): self.write(self.SPACE() + ('R%.3f' % radius)) if (length != None): self.write(self.SPACE() + 'Z%.3f' % length) self.write('\n') def offset_radius(self, id, radius=None): pass def offset_length(self, id, length=None): pass ############################################################################ ## Datums def datum_shift(self, x=None, y=None, z=None, a=None, b=None, c=None): pass def datum_set(self, x=None, y=None, z=None, a=None, b=None, c=None): pass # This is the coordinate system we're using. G54->G59, G59.1, G59.2, G59.3 # These are selected by values from 1 to 9 inclusive. def workplane(self, id): if ((id >= 1) and (id <= 6)): self.g_list.append(self.WORKPLANE() % (id + self.WORKPLANE_BASE())) if ((id >= 7) and (id <= 9)): self.g_list.append(((self.WORKPLANE() % (6 + self.WORKPLANE_BASE())) + ('.%i' % (id - 6)))) ############################################################################ ## Rates + Modes def feedrate(self, f): self.f.set(f) self.fhv = False def feedrate_hv(self, fh, fv): self.fh = fh self.fv = fv self.fhv = True def calc_feedrate_hv(self, h, v): if math.fabs(v) > math.fabs(h * 2): # some horizontal, so it should be fine to use the horizontal feed rate self.f.set(self.fv) else: # not much, if any horizontal component, so use the vertical feed rate self.f.set(self.fh) def spindle(self, s, clockwise): if clockwise == True: self.s.set(s, self.SPACE() + self.SPINDLE_CW(), self.SPACE() + self.SPINDLE_CCW()) else: self.s.set(s, self.SPACE() + self.SPINDLE_CCW(), self.SPACE() + self.SPINDLE_CW()) def coolant(self, mode=0): if (mode <= 0) : self.m.append(self.SPACE() + self.COOLANT_OFF()) elif (mode == 1) : self.m.append(self.SPACE() + self.COOLANT_MIST()) elif (mode == 2) : self.m.append(self.SPACE() + self.COOLANT_FLOOD()) def gearrange(self, gear=0): if (gear <= 0) : self.m.append(self.SPACE() + self.GEAR_OFF()) elif (gear <= 4) : self.m.append(self.SPACE() + self.GEAR() % (gear + GEAR_BASE())) ############################################################################ ## Moves def rapid(self, x=None, y=None, z=None, a=None, b=None, c=None, machine_coordinates=None ): self.write_blocknum() if self.machine_coordinates != False or (machine_coordinates != None and machine_coordinates == True): self.write( self.MACHINE_COORDINATES() + self.SPACE() ) if self.g0123_modal: if self.prev_g0123 != self.RAPID(): self.write(self.SPACE() + self.RAPID()) self.prev_g0123 = self.RAPID() else: self.write(self.SPACE() + self.RAPID()) self.write_preps() if (x != None): dx = x - self.x if (self.absolute_flag ): self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) else: self.write(self.SPACE() + self.X() + (self.fmt.string(dx))) self.x = x if (y != None): dy = y - self.y if (self.absolute_flag ): self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) else: self.write(self.SPACE() + self.Y() + (self.fmt.string(dy))) self.y = y if (z != None): dz = z - self.z if (self.absolute_flag ): self.write(self.SPACE() + self.Z() + (self.fmt.string(z + self.shift_z))) else: self.write(self.SPACE() + self.Z() + (self.fmt.string(dz))) self.z = z if (a != None): da = a - self.a if (self.absolute_flag ): self.write(self.SPACE() + self.A() + (self.fmt.string(a))) else: self.write(self.SPACE() + self.A() + (self.fmt.string(da))) self.a = a if (b != None): db = b - self.b if (self.absolute_flag ): self.write(self.SPACE() + self.B() + (self.fmt.string(b))) else: self.write(self.SPACE() + self.B() + (self.fmt.string(db))) self.b = b if (c != None): dc = c - self.c if (self.absolute_flag ): self.write(self.SPACE() + self.C() + (self.fmt.string(c))) else: self.write(self.SPACE() + self.C() + (self.fmt.string(dc))) self.c = c self.write_spindle() self.write_misc() self.write('\n') def feed(self, x=None, y=None, z=None): if self.same_xyz(x, y, z): return self.write_blocknum() if self.g0123_modal: if self.prev_g0123 != self.FEED(): self.write(self.SPACE() + self.FEED()) self.prev_g0123 = self.FEED() else: self.write(self.FEED()) self.write_preps() dx = dy = dz = 0 if (x != None): dx = x - self.x if (self.absolute_flag ): self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) else: self.write(self.SPACE() + self.X() + (self.fmt.string(dx))) self.x = x if (y != None): dy = y - self.y if (self.absolute_flag ): self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) else: self.write(self.SPACE() + self.Y() + (self.fmt.string(dy))) self.y = y if (z != None): dz = z - self.z if (self.absolute_flag ): self.write(self.SPACE() + self.Z() + (self.fmt.string(z + self.shift_z))) else: self.write(self.SPACE() + self.Z() + (self.fmt.string(dz))) self.z = z if (self.fhv) : self.calc_feedrate_hv(math.sqrt(dx*dx+dy*dy), math.fabs(dz)) self.write_feedrate() self.write_spindle() self.write_misc() self.write('\n') def same_xyz(self, x=None, y=None, z=None): if (x != None): if (self.fmt.string(x + self.shift_x)) != (self.fmt.string(self.x)): return False if (y != None): if (self.fmt.string(y + self.shift_y)) != (self.fmt.string(self.y)): return False if (z != None): if (self.fmt.string(z + self.shift_z)) != (self.fmt.string(self.z)): return False return True def get_quadrant(self, dx, dy): if dx < 0: if dy < 0: return 2 else: return 1 else: if dy < 0: return 3 else: return 0 def quadrant_start(self, q, i, j, rad): while q > 3: q = q - 4 if q == 0: return i + rad, j if q == 1: return i, j + rad if q == 2: return i - rad, j return i, j - rad def quadrant_end(self, q, i, j, rad): return self.quadrant_start(q + 1, i, j, rad) def get_arc_angle(self, sdx, sdy, edx, edy, cw): angle_s = math.atan2(sdy, sdx); angle_e = math.atan2(edy, edx); if cw: if angle_s < angle_e: angle_s = angle_s + 2 * math.pi else: if angle_e < angle_s: angle_e = angle_e + 2 * math.pi return angle_e - angle_s def arc(self, cw, x=None, y=None, z=None, i=None, j=None, k=None, r=None): if self.same_xyz(x, y, z): return if self.can_do_helical_arcs == False and self.in_quadrant_splitting == False and (z != None) and (math.fabs(z - self.z) > 0.000001) and (self.fmt.string(z) != self.fmt.string(self.z)): # split the helical arc into little line feed moves if x == None: x = self.x if y == None: y = self.y sdx = self.x - i sdy = self.y - j edx = x - i edy = y - j radius = math.sqrt(sdx*sdx + sdy*sdy) arc_angle = self.get_arc_angle(sdx, sdy, edx, edy, cw) angle_start = math.atan2(sdy, sdx); tolerance = 0.02 angle_step = 2.0 * math.atan( math.sqrt ( tolerance /(radius - tolerance) )) segments = int(math.fabs(arc_angle / angle_step) + 1) angle_step = arc_angle / segments angle = angle_start z_step = float(z - self.z)/segments next_z = self.z for p in range(0, segments): angle = angle + angle_step next_x = i + radius * math.cos(angle) next_y = j + radius * math.sin(angle) next_z = next_z + z_step self.feed(next_x, next_y, next_z) return if self.arc_centre_positive == True and self.in_quadrant_splitting == False: # split in to quadrant arcs self.in_quadrant_splitting = True if x == None: x = self.x if y == None: y = self.y sdx = self.x - i sdy = self.y - j edx = x - i edy = y - j qs = self.get_quadrant(sdx, sdy) qe = self.get_quadrant(edx, edy) if qs == qe: arc_angle = math.fabs(self.get_arc_angle(sdx, sdy, edx, edy, cw)) # arc_angle will be either less than pi/2 or greater than 3pi/2 if arc_angle > 3.14: if cw: qs = qs + 4 else: qe = qe + 4 if qs == qe: self.arc(cw, x, y, z, i, j, k, r) else: rad = math.sqrt(sdx * sdx + sdy * sdy) if cw: if qs < qe: qs = qs + 4 else: if qe < qs: qe = qe + 4 q = qs while 1: x1 = x y1 = y if q != qe: if cw: x1, y1 = self.quadrant_start(q, i, j, rad) else: x1, y1 = self.quadrant_end(q, i, j, rad) if (self.fmt.string(x1) != self.fmt.string(self.x)) or (self.fmt.string(y1) != self.fmt.string(self.y)): if (math.fabs(x1 - self.x) > 0.01) or (math.fabs(y1 - self.y) > 0.01): self.arc(cw, x1, y1, z, i, j, k, r) else: self.feed(x1, y1, z) if q == qe: break if cw: q = q - 1 else: q = q + 1 self.in_quadrant_splitting = False return #if self.same_xyz(x, y, z): return self.write_blocknum() arc_g_code = '' if cw: arc_g_code = self.ARC_CW() else: arc_g_code = self.ARC_CCW() if self.g0123_modal: if self.prev_g0123 != arc_g_code: self.write(arc_g_code) self.prev_g0123 = arc_g_code else: self.write(arc_g_code) self.write_preps() if (x != None): dx = x - self.x if (self.absolute_flag ): self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) else: self.write(self.SPACE() + self.X() + (self.fmt.string(dx))) if (y != None): dy = y - self.y if (self.absolute_flag ): self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) else: self.write(self.SPACE() + self.Y() + (self.fmt.string(dy))) if (z != None): dz = z - self.z if (self.absolute_flag ): self.write(self.SPACE() + self.Z() + (self.fmt.string(z + self.shift_z))) else: self.write(self.SPACE() + self.Z() + (self.fmt.string(dz))) if (i != None): if self.arc_centre_absolute == False: i = i - self.x s = self.fmt.string(i) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.CENTRE_X() + s) if (j != None): if self.arc_centre_absolute == False: j = j - self.y s = self.fmt.string(j) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.CENTRE_Y() + s) if (k != None): if self.arc_centre_absolute == False: k = k - self.z s = self.fmt.string(k) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.CENTRE_Z() + s) if (r != None): s = self.fmt.string(r) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.RADIUS() + s) # use horizontal feed rate if (self.fhv) : self.calc_feedrate_hv(1, 0) self.write_feedrate() self.write_spindle() self.write_misc() self.write('\n') if (x != None): self.x = x if (y != None): self.y = y if (z != None): self.z = z def arc_cw(self, x=None, y=None, z=None, i=None, j=None, k=None, r=None): self.arc(True, x, y, z, i, j, k, r) def arc_ccw(self, x=None, y=None, z=None, i=None, j=None, k=None, r=None): self.arc(False, x, y, z, i, j, k, r) def dwell(self, t): self.write_blocknum() self.write_preps() self.write(self.FORMAT_DWELL() % t) self.write_misc() self.write('\n') def rapid_home(self, x=None, y=None, z=None, a=None, b=None, c=None, machine_coordinates=None): pass def rapid_unhome(self): pass def set_machine_coordinates(self): self.write(self.SPACE() + self.MACHINE_COORDINATES()) self.prev_g0123 = '' ############################################################################ ## CRC def use_CRC(self): return self.useCrc def CRC_nominal_path(self): return self.useCrcCenterline def start_CRC(self, left = True, radius = 0.0): # set up prep code, to be output on next line if self.t == None: raise "No tool specified for start_CRC()" self.write_blocknum() if left: self.write(self.SPACE() + 'G41') else: self.write(self.SPACE() + 'G42') self.write((self.SPACE() + 'D%i\n') % self.t) def end_CRC(self): self.write_blocknum() self.write(self.SPACE() + 'G40\n') ############################################################################ ## Cycles def pattern(self): pass def pocket(self): pass def profile(self): pass # The drill routine supports drilling (G81), drilling with dwell (G82) and peck drilling (G83). # The x,y,z values are INITIAL locations (above the hole to be made. This is in contrast to # the Z value used in the G8[1-3] cycles where the Z value is that of the BOTTOM of the hole. # Instead, this routine combines the Z value and the depth value to determine the bottom of # the hole. # # The standoff value is the distance up from the 'z' value (normally just above the surface) where the bit retracts # to in order to clear the swarf. This combines with 'z' to form the 'R' value in the G8[1-3] cycles. # # The peck_depth value is the incremental depth (Q value) that tells the peck drilling # cycle how deep to go on each peck until the full depth is achieved. # # NOTE: This routine forces the mode to absolute mode so that the values passed into # the G8[1-3] cycles make sense. I don't know how to find the mode to revert it so I won't # revert it. I must set the mode so that I can be sure the values I'm passing in make # sense to the end-machine. # def drill(self, x=None, y=None, z=None, depth=None, standoff=None, dwell=None, peck_depth=None, retract_mode=None, spindle_mode=None): if (standoff == None): # This is a bad thing. All the drilling cycles need a retraction (and starting) height. return if (z == None): return # We need a Z value as well. This input parameter represents the top of the hole if self.drillExpanded: # for machines which don't understand G81, G82 etc. if peck_depth == None: peck_depth = depth current_z = z self.rapid(x, y) first = True while True: next_z = current_z - peck_depth if next_z < z - depth: next_z = z - depth if next_z >= current_z: break; if first: self.rapid(z = z + standoff) else: self.rapid(z = current_z) self.feed(z = next_z) self.rapid(z = z + standoff) current_z = next_z if dwell: self.dwell(dwell) first = False # we should pass clearance height into here, but my machine is on and I'm in a hurry... 22nd June 2011 danheeks self.rapid(z = z + 5.0) return self.write_preps() self.write_blocknum() if (peck_depth != 0): # We're pecking. Let's find a tree. if self.drill_modal: if self.PECK_DRILL() + self.PECK_DEPTH(self.fmt, peck_depth) != self.prev_drill: self.write(self.SPACE() + self.PECK_DRILL() + self.SPACE() + self.PECK_DEPTH(self.fmt, peck_depth)) self.prev_drill = self.PECK_DRILL() + self.PECK_DEPTH(self.fmt, peck_depth) else: self.write(self.PECK_DRILL() + self.PECK_DEPTH(self.fmt, peck_depth)) else: # We're either just drilling or drilling with dwell. if (dwell == 0): # We're just drilling. if self.drill_modal: if self.DRILL() != self.prev_drill: self.write(self.SPACE() + self.DRILL()) self.prev_drill = self.DRILL() else: self.write(self.SPACE() + self.DRILL()) else: # We're drilling with dwell. if self.drill_modal: if self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell) != self.prev_drill: self.write(self.SPACE() + self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell)) self.prev_drill = self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell) else: self.write(self.SPACE() + self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell)) #self.write(self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell)) # Set the retraction point to the 'standoff' distance above the starting z height. retract_height = z + standoff if (x != None): dx = x - self.x self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) self.x = x if (y != None): dy = y - self.y self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) self.y = y dz = (z + standoff) - self.z # In the end, we will be standoff distance above the z value passed in. if self.drill_modal: if z != self.prev_z: self.write(self.SPACE() + self.Z() + (self.fmt.string(z - depth))) self.prev_z=z else: self.write(self.SPACE() + self.Z() + (self.fmt.string(z - depth))) # This is the 'z' value for the bottom of the hole. self.z = (z + standoff) # We want to remember where z is at the end (at the top of the hole) if self.drill_modal: if self.prev_retract != self.RETRACT(self.fmt, retract_height) : self.write(self.SPACE() + self.RETRACT(self.fmt, retract_height)) self.prev_retract = self.RETRACT(self.fmt, retract_height) else: self.write(self.SPACE() + self.RETRACT(self.fmt, retract_height)) if (self.fhv) : self.calc_feedrate_hv(math.sqrt(dx*dx+dy*dy), math.fabs(dz)) self.write_feedrate() self.write_spindle() self.write_misc() self.write('\n') # G33.1 tapping with EMC for now # unsynchronized (chuck) taps NIY (tap_mode = 1) def tap(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, pitch=None, stoppos=None, spin_in=None, spin_out=None, tap_mode=None, direction=None): # mystery parameters: # zretract=None, dwell_bottom=None,pitch=None, stoppos=None, spin_in=None, spin_out=None): # I dont see how to map these to EMC Gcode if (standoff == None): # This is a bad thing. All the drilling cycles need a retraction (and starting) height. return if (z == None): return # We need a Z value as well. This input parameter represents the top of the hole if (pitch == None): return # We need a pitch value. if (direction == None): return # We need a direction value. if (tap_mode != 0): raise "only rigid tapping currently supported" self.write_preps() self.write_blocknum() self.write_spindle() self.write('\n') # rapid to starting point; z first, then x,y iff given # Set the retraction point to the 'standoff' distance above the starting z height. retract_height = z + standoff # unsure if this is needed: if self.z != retract_height: self.rapid(z = retract_height) # then continue to x,y if given if (x != None) or (y != None): self.write_blocknum() self.write(self.RAPID() ) if (x != None): self.write(self.X() + self.fmt.string(x + self.shift_x)) self.x = x if (y != None): self.write(self.Y() + self.fmt.string(y + self.shift_y)) self.y = y self.write('\n') self.write_blocknum() self.write( self.TAP() ) self.write( self.TAP_DEPTH(self.ffmt,pitch) + self.SPACE() ) self.write(self.Z() + self.fmt.string(z - depth))# This is the 'z' value for the bottom of the tap. self.write_misc() self.write('\n') self.z = retract_height # this cycle returns to the start position, so remember that as z value def bore(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, feed_in=None, feed_out=None, stoppos=None, shift_back=None, shift_right=None, backbore=False, stop=False): pass def end_canned_cycle(self): if self.drillExpanded: return self.write_blocknum() self.write(self.SPACE() + self.END_CANNED_CYCLE() + '\n') self.prev_drill = '' self.prev_g0123 = '' self.prev_z = '' self.prev_f = '' self.prev_retract = '' ############################################################################ ## Misc def comment(self, text): self.write((self.COMMENT(text) + '\n')) def insert(self, text): pass def block_delete(self, on=False): pass def variable(self, id): return (self.VARIABLE() % id) def variable_set(self, id, value): self.write_blocknum() self.write(self.SPACE() + (self.VARIABLE() % id) + self.SPACE() + (self.VARIABLE_SET() % value) + '\n') # This routine uses the G92 coordinate system offsets to establish a temporary coordinate # system at the machine's current position. It can then use absolute coordinates relative # to this position which makes coding easy. It then moves to the 'point along edge' which # should be above the workpiece but still on one edge. It then backs off from the edge # to the 'retracted point'. It then plunges down by the depth value specified. It then # probes back towards the 'destination point'. The probed X,Y location are stored # into the 'intersection variable' variables. Finally the machine moves back to the # original location. This is important so that the results of multiple calls to this # routine may be compared meaningfully. def probe_single_point(self, point_along_edge_x=None, point_along_edge_y=None, depth=None, retracted_point_x=None, retracted_point_y=None, destination_point_x=None, destination_point_y=None, intersection_variable_x=None, intersection_variable_y=None, probe_offset_x_component=None, probe_offset_y_component=None ): self.write_blocknum() self.write(self.SPACE() + (self.SET_TEMPORARY_COORDINATE_SYSTEM() + (' X 0 Y 0 Z 0') + ('\t(Temporarily make this the origin)\n'))) if (self.fhv) : self.calc_feedrate_hv(1, 0) self.write_blocknum() self.write_feedrate() self.write('\t(Set the feed rate for probing)\n') self.rapid(point_along_edge_x,point_along_edge_y) self.rapid(retracted_point_x,retracted_point_y) self.feed(z=depth) self.write_blocknum() self.write((self.PROBE_TOWARDS_WITH_SIGNAL() + (' X ' + (self.fmt.string(destination_point_x)) + ' Y ' + (self.fmt.string(destination_point_y)) ) + ('\t(Probe towards our destination point)\n'))) self.comment('Back off the workpiece and re-probe more slowly') self.write_blocknum() self.write(self.SPACE() + ('#' + intersection_variable_x + '= [#5061 - [ 0.5 * ' + probe_offset_x_component + ']]\n')) self.write_blocknum() self.write(self.SPACE() + ('#' + intersection_variable_y + '= [#5062 - [ 0.5 * ' + probe_offset_y_component + ']]\n')) self.write_blocknum(); self.write(self.RAPID()) self.write(self.SPACE() + ' X #' + intersection_variable_x + ' Y #' + intersection_variable_y + '\n') self.write_blocknum() self.write(self.SPACE() + self.FEEDRATE() + self.ffmt.string(self.fh / 2.0) + '\n') self.write_blocknum() self.write((self.SPACE() + self.PROBE_TOWARDS_WITH_SIGNAL() + (' X ' + (self.fmt.string(destination_point_x)) + ' Y ' + (self.fmt.string(destination_point_y)) ) + ('\t(Probe towards our destination point)\n'))) self.comment('Store the probed location somewhere we can get it again later') self.write_blocknum() self.write(('#' + intersection_variable_x + '=' + probe_offset_x_component + ' (Portion of probe radius that contributes to the X coordinate)\n')) self.write_blocknum() self.write(('#' + intersection_variable_x + '=[#' + intersection_variable_x + ' + #5061]\n')) self.write_blocknum() self.write(('#' + intersection_variable_y + '=' + probe_offset_y_component + ' (Portion of probe radius that contributes to the Y coordinate)\n')) self.write_blocknum() self.write(('#' + intersection_variable_y + '=[#' + intersection_variable_y + ' + #5062]\n')) self.comment('Now move back to the original location') self.rapid(retracted_point_x,retracted_point_y) self.rapid(z=0) self.rapid(point_along_edge_x,point_along_edge_y) self.rapid(x=0, y=0) self.write_blocknum() self.write((self.REMOVE_TEMPORARY_COORDINATE_SYSTEM() + ('\t(Restore the previous coordinate system)\n'))) def probe_downward_point(self, x=None, y=None, depth=None, intersection_variable_z=None): self.write_blocknum() self.write((self.SET_TEMPORARY_COORDINATE_SYSTEM() + (' X 0 Y 0 Z 0') + ('\t(Temporarily make this the origin)\n'))) if (self.fhv) : self.calc_feedrate_hv(1, 0) self.write_blocknum() self.write(self.FEEDRATE() + ' [' + self.ffmt.string(self.fh) + ' / 5.0 ]') self.write('\t(Set the feed rate for probing)\n') if x != None and y != None: self.write_blocknum(); self.write(self.RAPID()) self.write(' X ' + x + ' Y ' + y + '\n') self.write_blocknum() self.write((self.PROBE_TOWARDS_WITH_SIGNAL() + ' Z ' + (self.fmt.string(depth)) + ('\t(Probe towards our destination point)\n'))) self.comment('Store the probed location somewhere we can get it again later') self.write_blocknum() self.write(('#' + intersection_variable_z + '= #5063\n')) self.comment('Now move back to the original location') self.rapid(z=0) self.rapid(x=0, y=0) self.write_blocknum() self.write((self.REMOVE_TEMPORARY_COORDINATE_SYSTEM() + ('\t(Restore the previous coordinate system)\n'))) def report_probe_results(self, x1=None, y1=None, z1=None, x2=None, y2=None, z2=None, x3=None, y3=None, z3=None, x4=None, y4=None, z4=None, x5=None, y5=None, z5=None, x6=None, y6=None, z6=None, xml_file_name=None ): pass def open_log_file(self, xml_file_name=None ): pass def log_coordinate(self, x=None, y=None, z=None): pass def log_message(self, message=None): pass def close_log_file(self): pass # Rapid movement to the midpoint between the two points specified. # NOTE: The points are specified either as strings representing numbers or as strings # representing variable names. This allows the HeeksCNC module to determine which # variable names are used in these various routines. def rapid_to_midpoint(self, x1=None, y1=None, z1=None, x2=None, y2=None, z2=None): self.write_blocknum() self.write(self.RAPID()) if ((x1 != None) and (x2 != None)): self.write((' X ' + '[[[' + x1 + ' - ' + x2 + '] / 2.0] + ' + x2 + ']')) if ((y1 != None) and (y2 != None)): self.write((' Y ' + '[[[' + y1 + ' - ' + y2 + '] / 2.0] + ' + y2 + ']')) if ((z1 != None) and (z2 != None)): self.write((' Z ' + '[[[' + z1 + ' - ' + z2 + '] / 2.0] + ' + z2 + ']')) self.write('\n') # Rapid movement to the intersection of two lines (in the XY plane only). This routine # is based on information found in http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ # written by Paul Bourke. The ua_numerator, ua_denominator, ua and ub parameters # represent variable names (with the preceding '#' included in them) for use as temporary # variables. They're specified here simply so that HeeksCNC can manage which variables # are used in which GCode calculations. # # As per the notes on the web page, the ua_denominator and ub_denominator formulae are # the same so we don't repeat this. If the two lines are coincident or parallel then # no movement occurs. # # NOTE: The points are specified either as strings representing numbers or as strings # representing variable names. This allows the HeeksCNC module to determine which # variable names are used in these various routines. def rapid_to_intersection(self, x1, y1, x2, y2, x3, y3, x4, y4, intersection_x, intersection_y, ua_numerator, ua_denominator, ua, ub_numerator, ub): self.comment('Find the intersection of the two lines made up by the four probed points') self.write_blocknum(); self.write(ua_numerator + '=[[[' + x4 + ' - ' + x3 + '] * [' + y1 + ' - ' + y3 + ']] - [[' + y4 + ' - ' + y3 + '] * [' + x1 + ' - ' + x3 + ']]]\n') self.write_blocknum(); self.write(ua_denominator + '=[[[' + y4 + ' - ' + y3 + '] * [' + x2 + ' - ' + x1 + ']] - [[' + x4 + ' - ' + x3 + '] * [' + y2 + ' - ' + y1 + ']]]\n') self.write_blocknum(); self.write(ub_numerator + '=[[[' + x2 + ' - ' + x1 + '] * [' + y1 + ' - ' + y3 + ']] - [[' + y2 + ' - ' + y1 + '] * [' + x1 + ' - ' + x3 + ']]]\n') self.comment('If they are not parallel') self.write('O900 IF [' + ua_denominator + ' NE 0]\n') self.comment('And if they are not coincident') self.write('O901 IF [' + ua_numerator + ' NE 0 ]\n') self.write_blocknum(); self.write(' ' + ua + '=[' + ua_numerator + ' / ' + ua_denominator + ']\n') self.write_blocknum(); self.write(' ' + ub + '=[' + ub_numerator + ' / ' + ua_denominator + ']\n') # NOTE: ub denominator is the same as ua denominator self.write_blocknum(); self.write(' ' + intersection_x + '=[' + x1 + ' + [[' + ua + ' * [' + x2 + ' - ' + x1 + ']]]]\n') self.write_blocknum(); self.write(' ' + intersection_y + '=[' + y1 + ' + [[' + ua + ' * [' + y2 + ' - ' + y1 + ']]]]\n') self.write_blocknum(); self.write(' ' + self.RAPID()) self.write(' X ' + intersection_x + ' Y ' + intersection_y + '\n') self.write('O901 ENDIF\n') self.write('O900 ENDIF\n') # We need to calculate the rotation angle based on the line formed by the # x1,y1 and x2,y2 coordinate pair. With that angle, we need to move # x_offset and y_offset distance from the current (0,0,0) position. # # The x1,y1,x2 and y2 parameters are all variable names that contain the actual # values. # The x_offset and y_offset are both numeric (floating point) values def rapid_to_rotated_coordinate(self, x1, y1, x2, y2, ref_x, ref_y, x_current, y_current, x_final, y_final): self.comment('Rapid to rotated coordinate') self.write_blocknum(); self.write( '#1 = [atan[' + y2 + ' - ' + y1 + ']/[' + x2 +' - ' + x1 + ']] (nominal_angle)\n') self.write_blocknum(); self.write( '#2 = [atan[' + ref_y + ']/[' + ref_x + ']] (reference angle)\n') self.write_blocknum(); self.write( '#3 = [#1 - #2] (angle)\n' ) self.write_blocknum(); self.write( '#4 = [[[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(x_current)) + '] * COS[ #3 ]] - [[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(y_current)) + '] * SIN[ #3 ]]]\n' ) self.write_blocknum(); self.write( '#5 = [[[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(x_current)) + '] * SIN[ #3 ]] + [[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(y_current)) + '] * COS[ #3 ]]]\n' ) self.write_blocknum(); self.write( '#6 = [[' + (self.fmt.string(x_final)) + ' * COS[ #3 ]] - [' + (self.fmt.string(y_final)) + ' * SIN[ #3 ]]]\n' ) self.write_blocknum(); self.write( '#7 = [[' + (self.fmt.string(y_final)) + ' * SIN[ #3 ]] + [' + (self.fmt.string(y_final)) + ' * COS[ #3 ]]]\n' ) self.write_blocknum(); self.write( self.RAPID() + ' X [ #4 + #6 ] Y [ #5 + #7 ]\n' ) def BEST_POSSIBLE_SPEED(self, motion_blending_tolerance, naive_cam_tolerance): statement = 'G64' if (motion_blending_tolerance > 0): statement += ' P ' + str(motion_blending_tolerance) if (naive_cam_tolerance > 0): statement += ' Q ' + str(naive_cam_tolerance) return(statement) def set_path_control_mode(self, mode, motion_blending_tolerance, naive_cam_tolerance ): self.write_blocknum() if (mode == 0): self.write( self.EXACT_PATH_MODE() + '\n' ) if (mode == 1): self.write( self.EXACT_STOP_MODE() + '\n' ) if (mode == 2): self.write( self.BEST_POSSIBLE_SPEED( motion_blending_tolerance, naive_cam_tolerance ) + '\n' )
def grouping(self, combine, schedule, priority_name): self.__algorithm.initialize(self.base_info) self.__algorithm.calculate(combine, schedule) result = self.__algorithm.final(priority_name) return Format(result)
def __init__(self, thisConfig, thisTitle, thisThreshold, thisDataType, thisDebug=True, thisSources='database'): Format.__init__(self, thisDebug) self.config = thisConfig self._title = thisTitle self._defaultThreshold = thisThreshold self._dataType = thisDataType # Annotate _doves, _phantoms, _worms and _chameleons self.debug = thisDebug self._sources = thisSources self._format = Format(self.debug) self._plotType = None # Target scores per label and meta value pattern. self._targetScores = collections.defaultdict(list) # Number of targets per label. self._targetCnt = collections.Counter() # Non target scores per label and meta value pattern. self._nonTargetScores = collections.defaultdict(list) # Number of non targets per label. self._nonTargetCnt = collections.Counter() # Target scores per label. self._targetScores4Label = collections.defaultdict(list) self._targetScores4MetaValue = collections.defaultdict(list) # Non target scores per label. self._nonTargetScores4Label = collections.defaultdict(list) self._nonTargetScores4MetaValue = collections.defaultdict(list) self._results = collections.defaultdict(list) self._results4Subject = collections.defaultdict(list) self._nrDistinctMetaDataValues = 0 # Contains: { speakerId: metaDataValue } self._metaDataValues = collections.defaultdict(set) self._LabelsToShowAlways = [] self._minimumScore = collections.defaultdict(dict) self._maximumScore = collections.defaultdict(dict) # Keep track of labels. self._targetLabels = set() self._nonTargetLabels = set() # Do we allow both scores (A vs B and B vs A) in a symmetric tests or only the first read? self._allowDups = self.config.getAllowDups() if self.debug: print('Data._source(s):') for el in self._sources: print(el) # If the user did not specify a filename, we assume a database as the source. if self._sources == 'database': print("You need to add some code for this to work!") # And remove the sys.exit(1) statement. sys.exit(1) res = self._readFromDatabase() else: res = self._readFromFiles(self._sources) # # Choose between decoder for type of results. # if self._dataType == 'type3': self._decodeType3Results(res) elif self._dataType == 'type2': print("Type2 data is not supported anymore. Convert it to type3!") sys.exit(1) elif self._dataType == 'type1': self._decodeType1Results(res) else: print("Unknown data type, must be 'type1' or 'type3'.") sys.exit(1)
class Creator(nc.Creator): def __init__(self): nc.Creator.__init__(self) self.a = 0 self.b = 0 self.c = 0 self.f = Address('F', fmt = Format(number_of_decimal_places = 2)) self.fh = None self.fv = None self.fhv = False self.g_plane = Address('G', fmt = Format(number_of_decimal_places = 0)) self.g_list = [] self.i = 0 self.j = 0 self.k = 0 self.m = [] self.n = 10 self.r = 0 self.s = AddressPlusMinus('S', fmt = Format(number_of_decimal_places = 2), modal = False) self.t = None self.x = 0 self.y = 0 self.z = 500 self.g0123_modal = False self.drill_modal = False self.prev_f = '' self.prev_g0123 = '' self.prev_drill = '' self.prev_retract = '' self.prev_z = '' self.useCrc = False self.useCrcCenterline = False self.gCRC = '' self.fmt = Format() self.absolute_flag = True self.ffmt = Format(number_of_decimal_places = 2) self.sfmt = Format(number_of_decimal_places = 1) self.arc_centre_absolute = False self.arc_centre_positive = False self.in_quadrant_splitting = False self.drillExpanded = False self.can_do_helical_arcs = True self.shift_x = 0.0 self.shift_y = 0.0 self.shift_z = 0.0 ############################################################################ ## Codes def SPACE(self): return('') def FORMAT_FEEDRATE(self): return('%.2f') def FORMAT_ANG(self): return('%.1f') def FORMAT_TIME(self): return('%.2f') def FORMAT_DWELL(self): return('P%f') def BLOCK(self): return('%i') def COMMENT(self,comment): return( ('(%s)' % comment ) ) def VARIABLE(self): return( '#%i') def VARIABLE_SET(self): return( '=%.3f') def SUBPROG_CALL(self): return( 'M98' + self.SPACE() + 'P%i') def SUBPROG_END(self): return( 'M99') def STOP_OPTIONAL(self): return('M01') def STOP(self): return('M00') def IMPERIAL(self): return('G20') def METRIC(self): return('G21') def ABSOLUTE(self): return('G90') def INCREMENTAL(self): return('G91') def SET_TEMPORARY_COORDINATE_SYSTEM(self): return('G92') def REMOVE_TEMPORARY_COORDINATE_SYSTEM(self): return('G92.1') def POLAR_ON(self): return('G16') def POLAR_OFF(self): return('G15') def PLANE_XY(self): return('17') def PLANE_XZ(self): return('18') def PLANE_YZ(self): return('19') def TOOL(self): return('T%i' + self.SPACE() + 'M06') def TOOL_DEFINITION(self): return('G10' + self.SPACE() + 'L1') def WORKPLANE(self): return('G%i') def WORKPLANE_BASE(self): return(53) def SPINDLE_CW(self): return('M03') def SPINDLE_CCW(self): return('M04') def COOLANT_OFF(self): return('M09') def COOLANT_MIST(self): return('M07') def COOLANT_FLOOD(self): return('M08') def GEAR_OFF(self): return('?') def GEAR(self): return('M%i') def GEAR_BASE(self): return(37) def RAPID(self): return('G00') def FEED(self): return('G01') def ARC_CW(self): return('G02') def ARC_CCW(self): return('G03') def DWELL(self): return('G04') def DRILL(self): return('G81') def DRILL_WITH_DWELL(self, format, dwell): return('G82' + self.SPACE() + (format.string(dwell))) def PECK_DRILL(self): return('G83') def PECK_DEPTH(self, format, depth): return(self.SPACE() + 'Q' + (format.string(depth))) def RETRACT(self, format, height): return(self.SPACE() + 'R' + (format.string(height))) def END_CANNED_CYCLE(self): return('G80') def TAP(self): return('G84') def TAP_DEPTH(self, format, depth): return(self.SPACE() + 'K' + (format.string(depth))) def X(self): return('X') def Y(self): return('Y') def Z(self): return('Z') def A(self): return('A') def B(self): return('B') def C(self): return('C') def CENTRE_X(self): return('I') def CENTRE_Y(self): return('J') def CENTRE_Z(self): return('K') def RADIUS(self): return('R') def TIME(self): return('P') def PROBE_TOWARDS_WITH_SIGNAL(self): return('G38.2') def PROBE_TOWARDS_WITHOUT_SIGNAL(self): return('G38.3') def PROBE_AWAY_WITH_SIGNAL(self): return('G38.4') def PROBE_AWAY_WITHOUT_SIGNAL(self): return('G38.5') def MACHINE_COORDINATES(self): return('G53') def EXACT_PATH_MODE(self): return('G61') def EXACT_STOP_MODE(self): return('G61.1') ############################################################################ ## Internals def write_feedrate(self): self.f.write(self) def write_preps(self): self.g_plane.write(self) for g in self.g_list: self.write(self.SPACE() + g) self.g_list = [] def write_misc(self): if (len(self.m)) : self.write(self.m.pop()) def write_blocknum(self): self.write(self.BLOCK() % self.n) self.n += 1 def write_spindle(self): self.s.write(self) ############################################################################ ## Programs def program_begin(self, id, name=''): #1 BEGIN PGM 0011 MM self.write_blocknum() self.program_id = id self.write(self.SPACE() + ('BEGIN PGM %i MM' % id)) self.write('\n') def program_stop(self, optional=False): self.write_blocknum() if (optional) : self.write(self.SPACE() + self.STOP_OPTIONAL() + '\n') self.prev_g0123 = '' else : self.write(self.STOP() + '\n') self.prev_g0123 = '' def program_end(self): self.write_blocknum() self.write(self.SPACE() + ('END PGM %i MM' % self.program_id) + '\n') def flush_nc(self): if len(self.g_list) == 0 and len(self.m) == 0: return self.write_blocknum() self.write_preps() self.write_misc() self.write('\n') ############################################################################ ## Subprograms def sub_begin(self, id, name=''): self.write((self.PROGRAM() % id) + self.SPACE() + (self.COMMENT(name))) self.write('\n') def sub_call(self, id): self.write_blocknum() self.write(self.SPACE() + (self.SUBPROG_CALL() % id) + '\n') def sub_end(self): self.write_blocknum() self.write(self.SPACE() + self.SUBPROG_END() + '\n') ############################################################################ ## Settings def imperial(self): self.g_list.append(self.IMPERIAL()) self.fmt.number_of_decimal_places = 4 def metric(self): self.g_list.append(self.METRIC()) self.fmt.number_of_decimal_places = 3 def absolute(self): self.g_list.append(self.ABSOLUTE()) self.absolute_flag = True def incremental(self): self.g_list.append(self.INCREMENTAL()) self.absolute_flag = False def polar(self, on=True): if (on) : self.g_list.append(self.POLAR_ON()) else : self.g_list.append(self.POLAR_OFF()) def set_plane(self, plane): if (plane == 0) : self.g_plane.set(self.PLANE_XY()) elif (plane == 1) : self.g_plane.set(self.PLANE_XZ()) elif (plane == 2) : self.g_plane.set(self.PLANE_YZ()) def set_temporary_origin(self, x=None, y=None, z=None, a=None, b=None, c=None): self.write_blocknum() self.write(self.SPACE() + (self.SET_TEMPORARY_COORDINATE_SYSTEM())) if (x != None): self.write( self.SPACE() + 'X ' + (self.fmt.string(x + self.shift_x)) ) if (y != None): self.write( self.SPACE() + 'Y ' + (self.fmt.string(y + self.shift_y)) ) if (z != None): self.write( self.SPACE() + 'Z ' + (self.fmt.string(z + self.shift_z)) ) if (a != None): self.write( self.SPACE() + 'A ' + (self.fmt.string(a)) ) if (b != None): self.write( self.SPACE() + 'B ' + (self.fmt.string(b)) ) if (c != None): self.write( self.SPACE() + 'C ' + (self.fmt.string(c)) ) self.write('\n') def remove_temporary_origin(self): self.write_blocknum() self.write(self.SPACE() + (self.REMOVE_TEMPORARY_COORDINATE_SYSTEM())) self.write('\n') ############################################################################ ## new graphics origin- make a new coordinate system and snap it onto the geometry ## the toolpath generated should be translated def translate(self,x=None, y=None, z=None): self.shift_x = -x self.shift_y = -y self.shift_z = -z ############################################################################ ## Tools def tool_change(self, id): self.write_blocknum() self.write(self.SPACE() + (self.TOOL() % id) + '\n') self.t = id def tool_defn(self, id, name='', params=None): self.write_blocknum() self.write(self.SPACE() + self.TOOL_DEFINITION()) self.write(self.SPACE() + ('P%i' % id) + ' ') if (radius != None): self.write(self.SPACE() + ('R%.3f' % (float(params['diameter'])/2))) if (length != None): self.write(self.SPACE() + 'Z%.3f' % float(params['cutting edge height'])) self.write('\n') def offset_radius(self, id, radius=None): pass def offset_length(self, id, length=None): pass def current_tool(self): return self.t ############################################################################ ## Datums def datum_shift(self, x=None, y=None, z=None, a=None, b=None, c=None): pass def datum_set(self, x=None, y=None, z=None, a=None, b=None, c=None): pass # This is the coordinate system we're using. G54->G59, G59.1, G59.2, G59.3 # These are selected by values from 1 to 9 inclusive. def workplane(self, id): if ((id >= 1) and (id <= 6)): self.g_list.append(self.WORKPLANE() % (id + self.WORKPLANE_BASE())) if ((id >= 7) and (id <= 9)): self.g_list.append(((self.WORKPLANE() % (6 + self.WORKPLANE_BASE())) + ('.%i' % (id - 6)))) ############################################################################ ## Rates + Modes def feedrate(self, f): self.f = self.SPACE() + self.FEEDRATE() + self.ffmt.string(f) self.fhv = False def feedrate_hv(self, fh, fv): self.fh = fh self.fv = fv self.fhv = True def calc_feedrate_hv(self, h, v): if math.fabs(v) > math.fabs(h * 2): # some horizontal, so it should be fine to use the horizontal feed rate self.f.set(self.fv) else: # not much, if any horizontal component, so use the vertical feed rate self.f.set(self.fh) def spindle(self, s, clockwise): if clockwise == True: self.s.set(s, self.SPACE() + self.SPINDLE_CW(), self.SPACE() + self.SPINDLE_CCW()) else: self.s.set(s, self.SPACE() + self.SPINDLE_CCW(), self.SPACE() + self.SPINDLE_CW()) def coolant(self, mode=0): if (mode <= 0) : self.m.append(self.SPACE() + self.COOLANT_OFF()) elif (mode == 1) : self.m.append(self.SPACE() + self.COOLANT_MIST()) elif (mode == 2) : self.m.append(self.SPACE() + self.COOLANT_FLOOD()) def gearrange(self, gear=0): if (gear <= 0) : self.m.append(self.SPACE() + self.GEAR_OFF()) elif (gear <= 4) : self.m.append(self.SPACE() + self.GEAR() % (gear + GEAR_BASE())) ############################################################################ ## Moves def rapid(self, x=None, y=None, z=None, a=None, b=None, c=None ): self.write_blocknum() if self.g0123_modal: if self.prev_g0123 != self.RAPID(): self.write(self.SPACE() + self.RAPID()) self.prev_g0123 = self.RAPID() else: self.write(self.SPACE() + self.RAPID()) self.write_preps() if (x != None): dx = x - self.x if (self.absolute_flag ): self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) else: self.write(self.SPACE() + self.X() + (self.fmt.string(dx))) self.x = x if (y != None): dy = y - self.y if (self.absolute_flag ): self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) else: self.write(self.SPACE() + self.Y() + (self.fmt.string(dy))) self.y = y if (z != None): dz = z - self.z if (self.absolute_flag ): self.write(self.SPACE() + self.Z() + (self.fmt.string(z + self.shift_z))) else: self.write(self.SPACE() + self.Z() + (self.fmt.string(dz))) self.z = z if (a != None): da = a - self.a if (self.absolute_flag ): self.write(self.SPACE() + self.A() + (self.fmt.string(a))) else: self.write(self.SPACE() + self.A() + (self.fmt.string(da))) self.a = a if (b != None): db = b - self.b if (self.absolute_flag ): self.write(self.SPACE() + self.B() + (self.fmt.string(b))) else: self.write(self.SPACE() + self.B() + (self.fmt.string(db))) self.b = b if (c != None): dc = c - self.c if (self.absolute_flag ): self.write(self.SPACE() + self.C() + (self.fmt.string(c))) else: self.write(self.SPACE() + self.C() + (self.fmt.string(dc))) self.c = c self.write_spindle() self.write_misc() self.write('\n') def feed(self, x=None, y=None, z=None, a=None, b=None, c=None): if self.same_xyz(x, y, z): return self.write_blocknum() if self.g0123_modal: if self.prev_g0123 != self.FEED(): self.write(self.SPACE() + self.FEED()) self.prev_g0123 = self.FEED() else: self.write(self.FEED()) self.write_preps() dx = dy = dz = 0 if (x != None): dx = x - self.x if (self.absolute_flag ): self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) else: self.write(self.SPACE() + self.X() + (self.fmt.string(dx))) self.x = x if (y != None): dy = y - self.y if (self.absolute_flag ): self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) else: self.write(self.SPACE() + self.Y() + (self.fmt.string(dy))) self.y = y if (z != None): dz = z - self.z if (self.absolute_flag ): self.write(self.SPACE() + self.Z() + (self.fmt.string(z + self.shift_z))) else: self.write(self.SPACE() + self.Z() + (self.fmt.string(dz))) self.z = z if (self.fhv) : self.calc_feedrate_hv(math.sqrt(dx*dx+dy*dy), math.fabs(dz)) self.write_feedrate() self.write_spindle() self.write_misc() self.write('\n') def same_xyz(self, x=None, y=None, z=None): if (x != None): if (self.fmt.string(x + self.shift_x)) != (self.fmt.string(self.x)): return False if (y != None): if (self.fmt.string(y + self.shift_y)) != (self.fmt.string(self.y)): return False if (z != None): if (self.fmt.string(z + self.shift_z)) != (self.fmt.string(self.z)): return False return True def get_quadrant(self, dx, dy): if dx < 0: if dy < 0: return 2 else: return 1 else: if dy < 0: return 3 else: return 0 def quadrant_start(self, q, i, j, rad): while q > 3: q = q - 4 if q == 0: return i + rad, j if q == 1: return i, j + rad if q == 2: return i - rad, j return i, j - rad def quadrant_end(self, q, i, j, rad): return self.quadrant_start(q + 1, i, j, rad) def get_arc_angle(self, sdx, sdy, edx, edy, cw): angle_s = math.atan2(sdy, sdx); angle_e = math.atan2(edy, edx); if cw: if angle_s < angle_e: angle_s = angle_s + 2 * math.pi else: if angle_e < angle_s: angle_e = angle_e + 2 * math.pi return angle_e - angle_s def arc(self, cw, x=None, y=None, z=None, i=None, j=None, k=None, r=None): if self.can_do_helical_arcs == False and self.in_quadrant_splitting == False and (z != None) and (math.fabs(z - self.z) > 0.000001) and (self.fmt.string(z) != self.fmt.string(self.z)): # split the helical arc into little line feed moves if x == None: x = self.x if y == None: y = self.y sdx = self.x - i sdy = self.y - j edx = x - i edy = y - j radius = math.sqrt(sdx*sdx + sdy*sdy) arc_angle = self.get_arc_angle(sdx, sdy, edx, edy, cw) angle_start = math.atan2(sdy, sdx); tolerance = 0.02 angle_step = 2.0 * math.atan( math.sqrt ( tolerance /(radius - tolerance) )) segments = int(math.fabs(arc_angle / angle_step) + 1) angle_step = arc_angle / segments angle = angle_start z_step = float(z - self.z)/segments next_z = self.z for p in range(0, segments): angle = angle + angle_step next_x = i + radius * math.cos(angle) next_y = j + radius * math.sin(angle) next_z = next_z + z_step self.feed(next_x, next_y, next_z) return if self.arc_centre_positive == True and self.in_quadrant_splitting == False: # split in to quadrant arcs self.in_quadrant_splitting = True if x == None: x = self.x if y == None: y = self.y sdx = self.x - i sdy = self.y - j edx = x - i edy = y - j qs = self.get_quadrant(sdx, sdy) qe = self.get_quadrant(edx, edy) if qs == qe: arc_angle = math.fabs(self.get_arc_angle(sdx, sdy, edx, edy, cw)) # arc_angle will be either less than pi/2 or greater than 3pi/2 if arc_angle > 3.14: if cw: qs = qs + 4 else: qe = qe + 4 if qs == qe: self.arc(cw, x, y, z, i, j, k, r) else: rad = math.sqrt(sdx * sdx + sdy * sdy) if cw: if qs < qe: qs = qs + 4 else: if qe < qs: qe = qe + 4 q = qs while 1: x1 = x y1 = y if q != qe: if cw: x1, y1 = self.quadrant_start(q, i, j, rad) else: x1, y1 = self.quadrant_end(q, i, j, rad) if ((math.fabs(x1 - self.x) > 0.000001) or (math.fabs(y1 - self.y) > 0.000001)) and ((self.fmt.string(x1) != self.fmt.string(self.x)) or (self.fmt.string(y1) != self.fmt.string(self.y))): self.arc(cw, x1, y1, z, i, j, k, r) if q == qe: break if cw: q = q - 1 else: q = q + 1 self.in_quadrant_splitting = False return #if self.same_xyz(x, y, z): return self.write_blocknum() arc_g_code = '' if cw: arc_g_code = self.ARC_CW() else: arc_g_code = self.ARC_CCW() if self.g0123_modal: if self.prev_g0123 != arc_g_code: self.write(arc_g_code) self.prev_g0123 = arc_g_code else: self.write(arc_g_code) self.write_preps() if (x != None): dx = x - self.x if (self.absolute_flag ): self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) else: self.write(self.SPACE() + self.X() + (self.fmt.string(dx))) if (y != None): dy = y - self.y if (self.absolute_flag ): self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) else: self.write(self.SPACE() + self.Y() + (self.fmt.string(dy))) if (z != None): dz = z - self.z if (self.absolute_flag ): self.write(self.SPACE() + self.Z() + (self.fmt.string(z + self.shift_z))) else: self.write(self.SPACE() + self.Z() + (self.fmt.string(dz))) if (i != None): if self.arc_centre_absolute == False: i = i - self.x s = self.fmt.string(i) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.CENTRE_X() + s) if (j != None): if self.arc_centre_absolute == False: j = j - self.y s = self.fmt.string(j) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.CENTRE_Y() + s) if (k != None): if self.arc_centre_absolute == False: k = k - self.z s = self.fmt.string(k) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.CENTRE_Z() + s) if (r != None): s = self.fmt.string(r) if self.arc_centre_positive == True: if s[0] == '-': s = s[1:] self.write(self.SPACE() + self.RADIUS() + s) # use horizontal feed rate if (self.fhv) : self.calc_feedrate_hv(1, 0) self.write_feedrate() self.write_spindle() self.write_misc() self.write('\n') if (x != None): self.x = x if (y != None): self.y = y if (z != None): self.z = z def arc_cw(self, x=None, y=None, z=None, i=None, j=None, k=None, r=None): self.arc(True, x, y, z, i, j, k, r) def arc_ccw(self, x=None, y=None, z=None, i=None, j=None, k=None, r=None): self.arc(False, x, y, z, i, j, k, r) def dwell(self, t): self.write_blocknum() self.write_preps() self.write(self.FORMAT_DWELL() % t) self.write_misc() self.write('\n') def rapid_home(self, x=None, y=None, z=None, a=None, b=None, c=None): pass def rapid_unhome(self): pass def set_machine_coordinates(self): self.write(self.SPACE() + self.MACHINE_COORDINATES()) self.prev_g0123 = '' ############################################################################ ## CRC def use_CRC(self): return self.useCrc def CRC_nominal_path(self): return self.useCrcCenterline def start_CRC(self, left = True, radius = 0.0): # set up prep code, to be output on next line if self.t == None: raise "No tool specified for start_CRC()" self.write_blocknum() if left: self.write(self.SPACE() + 'G41') else: self.write(self.SPACE() + 'G42') self.write((self.SPACE() + 'D%i\n') % self.t) def end_CRC(self): self.write_blocknum() self.write(self.SPACE() + 'G40\n') ############################################################################ ## Cycles def pattern(self): pass def pocket(self): pass def profile(self): pass # The drill routine supports drilling (G81), drilling with dwell (G82) and peck drilling (G83). # The x,y,z values are INITIAL locations (above the hole to be made. This is in contrast to # the Z value used in the G8[1-3] cycles where the Z value is that of the BOTTOM of the hole. # Instead, this routine combines the Z value and the depth value to determine the bottom of # the hole. # # The standoff value is the distance up from the 'z' value (normally just above the surface) where the bit retracts # to in order to clear the swarf. This combines with 'z' to form the 'R' value in the G8[1-3] cycles. # # The peck_depth value is the incremental depth (Q value) that tells the peck drilling # cycle how deep to go on each peck until the full depth is achieved. # # NOTE: This routine forces the mode to absolute mode so that the values passed into # the G8[1-3] cycles make sense. I don't know how to find the mode to revert it so I won't # revert it. I must set the mode so that I can be sure the values I'm passing in make # sense to the end-machine. # def drill(self, x=None, y=None, dwell=None, depthparams = None, retract_mode=None, spindle_mode=None, internal_coolant_on=None, rapid_to_clearance = None): if (standoff == None): # This is a bad thing. All the drilling cycles need a retraction (and starting) height. return if (z == None): return # We need a Z value as well. This input parameter represents the top of the hole if self.drillExpanded: # for machines which don't understand G81, G82 etc. if peck_depth == None: peck_depth = depth current_z = z self.rapid(x, y) first = True while True: next_z = current_z - peck_depth if next_z < z - depth: next_z = z - depth if next_z >= current_z: break; if first: self.rapid(z = z + standoff) else: self.rapid(z = current_z) self.feed(z = next_z) self.rapid(z = z + standoff) current_z = next_z if dwell: self.dwell(dwell) first = False # we should pass clearance height into here, but my machine is on and I'm in a hurry... 22nd June 2011 danheeks self.rapid(z = z + 5.0) return self.write_preps() self.write_blocknum() if (peck_depth != 0): # We're pecking. Let's find a tree. if self.drill_modal: if self.PECK_DRILL() + self.PECK_DEPTH(self.fmt, peck_depth) != self.prev_drill: self.write(self.SPACE() + self.PECK_DRILL() + self.SPACE() + self.PECK_DEPTH(self.fmt, peck_depth)) self.prev_drill = self.PECK_DRILL() + self.PECK_DEPTH(self.fmt, peck_depth) else: self.write(self.PECK_DRILL() + self.PECK_DEPTH(self.fmt, peck_depth)) else: # We're either just drilling or drilling with dwell. if (dwell == 0): # We're just drilling. if self.drill_modal: if self.DRILL() != self.prev_drill: self.write(self.SPACE() + self.DRILL()) self.prev_drill = self.DRILL() else: self.write(self.SPACE() + self.DRILL()) else: # We're drilling with dwell. if self.drill_modal: if self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell) != self.prev_drill: self.write(self.SPACE() + self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell)) self.prev_drill = self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell) else: self.write(self.SPACE() + self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell)) #self.write(self.DRILL_WITH_DWELL(self.FORMAT_DWELL(),dwell)) # Set the retraction point to the 'standoff' distance above the starting z height. retract_height = z + standoff if (x != None): dx = x - self.x self.write(self.SPACE() + self.X() + (self.fmt.string(x + self.shift_x))) self.x = x if (y != None): dy = y - self.y self.write(self.SPACE() + self.Y() + (self.fmt.string(y + self.shift_y))) self.y = y dz = (z + standoff) - self.z # In the end, we will be standoff distance above the z value passed in. if self.drill_modal: if z != self.prev_z: self.write(self.SPACE() + self.Z() + (self.fmt.string(z - depth))) self.prev_z=z else: self.write(self.SPACE() + self.Z() + (self.fmt.string(z - depth))) # This is the 'z' value for the bottom of the hole. self.z = (z + standoff) # We want to remember where z is at the end (at the top of the hole) if self.drill_modal: if self.prev_retract != self.RETRACT(self.fmt, retract_height) : self.write(self.SPACE() + self.RETRACT(self.fmt, retract_height)) self.prev_retract = self.RETRACT(self.fmt, retract_height) else: self.write(self.SPACE() + self.RETRACT(self.fmt, retract_height)) if (self.fhv) : self.calc_feedrate_hv(math.sqrt(dx*dx+dy*dy), math.fabs(dz)) self.write_feedrate() self.write_spindle() self.write_misc() self.write('\n') # G33.1 tapping with EMC for now # unsynchronized (chuck) taps NIY (tap_mode = 1) def tap(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, pitch=None, stoppos=None, spin_in=None, spin_out=None, tap_mode=None, direction=None): # mystery parameters: # zretract=None, dwell_bottom=None,pitch=None, stoppos=None, spin_in=None, spin_out=None): # I dont see how to map these to EMC Gcode if (standoff == None): # This is a bad thing. All the drilling cycles need a retraction (and starting) height. return if (z == None): return # We need a Z value as well. This input parameter represents the top of the hole if (pitch == None): return # We need a pitch value. if (direction == None): return # We need a direction value. if (tap_mode != 0): raise "only rigid tapping currently supported" self.write_preps() self.write_blocknum() self.write_spindle() self.write('\n') # rapid to starting point; z first, then x,y iff given # Set the retraction point to the 'standoff' distance above the starting z height. retract_height = z + standoff # unsure if this is needed: if self.z != retract_height: self.rapid(z = retract_height) # then continue to x,y if given if (x != None) or (y != None): self.write_blocknum() self.write(self.RAPID() ) if (x != None): self.write(self.X() + self.fmt.string(x + self.shift_x)) self.x = x if (y != None): self.write(self.Y() + self.fmt.string(y + self.shift_y)) self.y = y self.write('\n') self.write_blocknum() self.write( self.TAP() ) self.write( self.TAP_DEPTH(self.ffmt,pitch) + self.SPACE() ) self.write(self.Z() + self.fmt.string(z - depth))# This is the 'z' value for the bottom of the tap. self.write_misc() self.write('\n') self.z = retract_height # this cycle returns to the start position, so remember that as z value def bore(self, x=None, y=None, z=None, zretract=None, depth=None, standoff=None, dwell_bottom=None, feed_in=None, feed_out=None, stoppos=None, shift_back=None, shift_right=None, backbore=False, stop=False): pass def end_canned_cycle(self): if self.drillExpanded: return self.write_blocknum() self.write(self.SPACE() + self.END_CANNED_CYCLE() + '\n') self.prev_drill = '' self.prev_g0123 = '' self.prev_z = '' self.prev_f = '' self.prev_retract = '' ############################################################################ ## Misc def comment(self, text): self.write((self.COMMENT(text) + '\n')) def insert(self, text): pass def block_delete(self, on=False): pass def variable(self, id): return (self.VARIABLE() % id) def variable_set(self, id, value): self.write_blocknum() self.write(self.SPACE() + (self.VARIABLE() % id) + self.SPACE() + (self.VARIABLE_SET() % value) + '\n') # This routine uses the G92 coordinate system offsets to establish a temporary coordinate # system at the machine's current position. It can then use absolute coordinates relative # to this position which makes coding easy. It then moves to the 'point along edge' which # should be above the workpiece but still on one edge. It then backs off from the edge # to the 'retracted point'. It then plunges down by the depth value specified. It then # probes back towards the 'destination point'. The probed X,Y location are stored # into the 'intersection variable' variables. Finally the machine moves back to the # original location. This is important so that the results of multiple calls to this # routine may be compared meaningfully. def probe_single_point(self, point_along_edge_x=None, point_along_edge_y=None, depth=None, retracted_point_x=None, retracted_point_y=None, destination_point_x=None, destination_point_y=None, intersection_variable_x=None, intersection_variable_y=None, probe_offset_x_component=None, probe_offset_y_component=None ): self.write_blocknum() self.write(self.SPACE() + (self.SET_TEMPORARY_COORDINATE_SYSTEM() + (' X 0 Y 0 Z 0') + ('\t(Temporarily make this the origin)\n'))) if (self.fhv) : self.calc_feedrate_hv(1, 0) self.write_blocknum() self.write_feedrate() self.write('\t(Set the feed rate for probing)\n') self.rapid(point_along_edge_x,point_along_edge_y) self.rapid(retracted_point_x,retracted_point_y) self.feed(z=depth) self.write_blocknum() self.write((self.PROBE_TOWARDS_WITH_SIGNAL() + (' X ' + (self.fmt.string(destination_point_x)) + ' Y ' + (self.fmt.string(destination_point_y)) ) + ('\t(Probe towards our destination point)\n'))) self.comment('Back off the workpiece and re-probe more slowly') self.write_blocknum() self.write(self.SPACE() + ('#' + intersection_variable_x + '= [#5061 - [ 0.5 * ' + probe_offset_x_component + ']]\n')) self.write_blocknum() self.write(self.SPACE() + ('#' + intersection_variable_y + '= [#5062 - [ 0.5 * ' + probe_offset_y_component + ']]\n')) self.write_blocknum(); self.write(self.RAPID()) self.write(self.SPACE() + ' X #' + intersection_variable_x + ' Y #' + intersection_variable_y + '\n') self.write_blocknum() self.write(self.SPACE() + self.FEEDRATE() + self.ffmt.string(self.fh / 2.0) + '\n') self.write_blocknum() self.write((self.SPACE() + self.PROBE_TOWARDS_WITH_SIGNAL() + (' X ' + (self.fmt.string(destination_point_x)) + ' Y ' + (self.fmt.string(destination_point_y)) ) + ('\t(Probe towards our destination point)\n'))) self.comment('Store the probed location somewhere we can get it again later') self.write_blocknum() self.write(('#' + intersection_variable_x + '=' + probe_offset_x_component + ' (Portion of probe radius that contributes to the X coordinate)\n')) self.write_blocknum() self.write(('#' + intersection_variable_x + '=[#' + intersection_variable_x + ' + #5061]\n')) self.write_blocknum() self.write(('#' + intersection_variable_y + '=' + probe_offset_y_component + ' (Portion of probe radius that contributes to the Y coordinate)\n')) self.write_blocknum() self.write(('#' + intersection_variable_y + '=[#' + intersection_variable_y + ' + #5062]\n')) self.comment('Now move back to the original location') self.rapid(retracted_point_x,retracted_point_y) self.rapid(z=0) self.rapid(point_along_edge_x,point_along_edge_y) self.rapid(x=0, y=0) self.write_blocknum() self.write((self.REMOVE_TEMPORARY_COORDINATE_SYSTEM() + ('\t(Restore the previous coordinate system)\n'))) def probe_downward_point(self, x=None, y=None, depth=None, intersection_variable_z=None): self.write_blocknum() self.write((self.SET_TEMPORARY_COORDINATE_SYSTEM() + (' X 0 Y 0 Z 0') + ('\t(Temporarily make this the origin)\n'))) if (self.fhv) : self.calc_feedrate_hv(1, 0) self.write_blocknum() self.write(self.FEEDRATE() + ' [' + self.ffmt.string(self.fh) + ' / 5.0 ]') self.write('\t(Set the feed rate for probing)\n') if x != None and y != None: self.write_blocknum(); self.write(self.RAPID()) self.write(' X ' + x + ' Y ' + y + '\n') self.write_blocknum() self.write((self.PROBE_TOWARDS_WITH_SIGNAL() + ' Z ' + (self.fmt.string(depth)) + ('\t(Probe towards our destination point)\n'))) self.comment('Store the probed location somewhere we can get it again later') self.write_blocknum() self.write(('#' + intersection_variable_z + '= #5063\n')) self.comment('Now move back to the original location') self.rapid(z=0) self.rapid(x=0, y=0) self.write_blocknum() self.write((self.REMOVE_TEMPORARY_COORDINATE_SYSTEM() + ('\t(Restore the previous coordinate system)\n'))) def report_probe_results(self, x1=None, y1=None, z1=None, x2=None, y2=None, z2=None, x3=None, y3=None, z3=None, x4=None, y4=None, z4=None, x5=None, y5=None, z5=None, x6=None, y6=None, z6=None, xml_file_name=None ): pass def open_log_file(self, xml_file_name=None ): pass def log_coordinate(self, x=None, y=None, z=None): pass def log_message(self, message=None): pass def close_log_file(self): pass # Rapid movement to the midpoint between the two points specified. # NOTE: The points are specified either as strings representing numbers or as strings # representing variable names. This allows the HeeksCNC module to determine which # variable names are used in these various routines. def rapid_to_midpoint(self, x1=None, y1=None, z1=None, x2=None, y2=None, z2=None): self.write_blocknum() self.write(self.RAPID()) if ((x1 != None) and (x2 != None)): self.write((' X ' + '[[[' + x1 + ' - ' + x2 + '] / 2.0] + ' + x2 + ']')) if ((y1 != None) and (y2 != None)): self.write((' Y ' + '[[[' + y1 + ' - ' + y2 + '] / 2.0] + ' + y2 + ']')) if ((z1 != None) and (z2 != None)): self.write((' Z ' + '[[[' + z1 + ' - ' + z2 + '] / 2.0] + ' + z2 + ']')) self.write('\n') # Rapid movement to the intersection of two lines (in the XY plane only). This routine # is based on information found in http://local.wasp.uwa.edu.au/~pbourke/geometry/lineline2d/ # written by Paul Bourke. The ua_numerator, ua_denominator, ua and ub parameters # represent variable names (with the preceding '#' included in them) for use as temporary # variables. They're specified here simply so that HeeksCNC can manage which variables # are used in which GCode calculations. # # As per the notes on the web page, the ua_denominator and ub_denominator formulae are # the same so we don't repeat this. If the two lines are coincident or parallel then # no movement occurs. # # NOTE: The points are specified either as strings representing numbers or as strings # representing variable names. This allows the HeeksCNC module to determine which # variable names are used in these various routines. def rapid_to_intersection(self, x1, y1, x2, y2, x3, y3, x4, y4, intersection_x, intersection_y, ua_numerator, ua_denominator, ua, ub_numerator, ub): self.comment('Find the intersection of the two lines made up by the four probed points') self.write_blocknum(); self.write(ua_numerator + '=[[[' + x4 + ' - ' + x3 + '] * [' + y1 + ' - ' + y3 + ']] - [[' + y4 + ' - ' + y3 + '] * [' + x1 + ' - ' + x3 + ']]]\n') self.write_blocknum(); self.write(ua_denominator + '=[[[' + y4 + ' - ' + y3 + '] * [' + x2 + ' - ' + x1 + ']] - [[' + x4 + ' - ' + x3 + '] * [' + y2 + ' - ' + y1 + ']]]\n') self.write_blocknum(); self.write(ub_numerator + '=[[[' + x2 + ' - ' + x1 + '] * [' + y1 + ' - ' + y3 + ']] - [[' + y2 + ' - ' + y1 + '] * [' + x1 + ' - ' + x3 + ']]]\n') self.comment('If they are not parallel') self.write('O900 IF [' + ua_denominator + ' NE 0]\n') self.comment('And if they are not coincident') self.write('O901 IF [' + ua_numerator + ' NE 0 ]\n') self.write_blocknum(); self.write(' ' + ua + '=[' + ua_numerator + ' / ' + ua_denominator + ']\n') self.write_blocknum(); self.write(' ' + ub + '=[' + ub_numerator + ' / ' + ua_denominator + ']\n') # NOTE: ub denominator is the same as ua denominator self.write_blocknum(); self.write(' ' + intersection_x + '=[' + x1 + ' + [[' + ua + ' * [' + x2 + ' - ' + x1 + ']]]]\n') self.write_blocknum(); self.write(' ' + intersection_y + '=[' + y1 + ' + [[' + ua + ' * [' + y2 + ' - ' + y1 + ']]]]\n') self.write_blocknum(); self.write(' ' + self.RAPID()) self.write(' X ' + intersection_x + ' Y ' + intersection_y + '\n') self.write('O901 ENDIF\n') self.write('O900 ENDIF\n') # We need to calculate the rotation angle based on the line formed by the # x1,y1 and x2,y2 coordinate pair. With that angle, we need to move # x_offset and y_offset distance from the current (0,0,0) position. # # The x1,y1,x2 and y2 parameters are all variable names that contain the actual # values. # The x_offset and y_offset are both numeric (floating point) values def rapid_to_rotated_coordinate(self, x1, y1, x2, y2, ref_x, ref_y, x_current, y_current, x_final, y_final): self.comment('Rapid to rotated coordinate') self.write_blocknum(); self.write( '#1 = [atan[' + y2 + ' - ' + y1 + ']/[' + x2 +' - ' + x1 + ']] (nominal_angle)\n') self.write_blocknum(); self.write( '#2 = [atan[' + ref_y + ']/[' + ref_x + ']] (reference angle)\n') self.write_blocknum(); self.write( '#3 = [#1 - #2] (angle)\n' ) self.write_blocknum(); self.write( '#4 = [[[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(x_current)) + '] * COS[ #3 ]] - [[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(y_current)) + '] * SIN[ #3 ]]]\n' ) self.write_blocknum(); self.write( '#5 = [[[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(x_current)) + '] * SIN[ #3 ]] + [[' + (self.fmt.string(0)) + ' - ' + (self.fmt.string(y_current)) + '] * COS[ #3 ]]]\n' ) self.write_blocknum(); self.write( '#6 = [[' + (self.fmt.string(x_final)) + ' * COS[ #3 ]] - [' + (self.fmt.string(y_final)) + ' * SIN[ #3 ]]]\n' ) self.write_blocknum(); self.write( '#7 = [[' + (self.fmt.string(y_final)) + ' * SIN[ #3 ]] + [' + (self.fmt.string(y_final)) + ' * COS[ #3 ]]]\n' ) self.write_blocknum(); self.write( self.RAPID() + ' X [ #4 + #6 ] Y [ #5 + #7 ]\n' ) def BEST_POSSIBLE_SPEED(self, motion_blending_tolerance, naive_cam_tolerance): statement = 'G64' if (motion_blending_tolerance > 0): statement += ' P ' + str(motion_blending_tolerance) if (naive_cam_tolerance > 0): statement += ' Q ' + str(naive_cam_tolerance) return(statement) def set_path_control_mode(self, mode, motion_blending_tolerance, naive_cam_tolerance ): self.write_blocknum() if (mode == 0): self.write( self.EXACT_PATH_MODE() + '\n' ) if (mode == 1): self.write( self.EXACT_STOP_MODE() + '\n' ) if (mode == 2): self.write( self.BEST_POSSIBLE_SPEED( motion_blending_tolerance, naive_cam_tolerance ) + '\n' )
from cmd_view import CmdView from controller import Controller from data_visualiser import DataVis from validator import Validator from format import Format from database import Database from serialize import Pickle if __name__ == '__main__': view = CmdView() validator = Validator() format = Format() pickle = Pickle() db = Database('company.db') con = Controller(view, validator, format, pickle, db) view.controller_set(con) view.cmdloop()
def __init__(self, name, dictobj): self.Formats = [Format(dictionary) for dictionary in dictobj["Formats"]] self.Name = name self.Instructions = [Instruction(dictionary) for dictionary in dictobj["Instructions"]]
TYPE_CHUNK = 3 TYPE_LEVELSIZE = 4 TYPE_BLOCKCHANGE = 5 TYPE_BLOCKSET = 6 TYPE_SPAWNPOINT = 7 TYPE_PLAYERPOS = 8 TYPE_NINE = 9 TYPE_TEN = 10 TYPE_PLAYERDIR = 11 TYPE_PLAYERLEAVE = 12 TYPE_MESSAGE = 13 TYPE_ERROR = 14 TYPE_SMP = 255 TYPE_FORMATS = { TYPE_INITIAL: Format("bssb"), TYPE_KEEPALIVE: Format(""), TYPE_PRECHUNK: Format(""), TYPE_CHUNK: Format("hab"), TYPE_LEVELSIZE: Format("hhh"), TYPE_BLOCKCHANGE: Format("hhhbb"), TYPE_BLOCKSET: Format("hhhb"), TYPE_SPAWNPOINT: Format("bshhhbb"), TYPE_PLAYERPOS: Format("bhhhbb"), TYPE_NINE: Format("bbbbbb"), TYPE_TEN: Format("bbbb"), TYPE_PLAYERDIR: Format("bbb"), TYPE_PLAYERLEAVE: Format("b"), TYPE_MESSAGE: Format("bs"), TYPE_ERROR: Format("s"), TYPE_SMP: Format(""),
# -*- coding: utf-8 -*- """ Created on Mon Jan 6 16:16:43 2020 @author: YWu """ from format import Format if __name__ == '__main__': pts = 49 cols = [0, 5, 6, 8] rows = [12, 55] tool = 'TESTTESTTESTTESTTEST' film = 'TESTTESTTESTTEST' FORMAT = Format() FORMAT.create_new_format(tool, film, pts, cols, rows) FORMAT.del_format(tool, film) d = FORMAT.read_format_dict() print(d)
def __init__(self): iso.Creator.__init__(self) self.output_tool_definitions = False self.fmt = Format(dp_wanted=False, add_trailing_zeros=True, add_plus=True)
def __init__(self, thisConfig, thisTitle, thisThreshold, thisDataType, maxNrTargetSamplesPerLabel, maxNrNonTargetSamplesPerLabel, thisDebug=True, thisSources='database'): Format.__init__(self, thisDebug) self.config = thisConfig self._title = thisTitle self._defaultThreshold = thisThreshold self._dataType = thisDataType # Annotate _doves, _phantoms, _worms and _chameleons self._maxNrTargetSamplesPerLabel = maxNrTargetSamplesPerLabel self._maxNrNonTargetSamplesPerLabel = maxNrNonTargetSamplesPerLabel self.debug = thisDebug self._sources = thisSources self._format = Format(self.debug) self._plotType = None # Target scores per label and meta value pattern. self._targetScores = collections.defaultdict(list) # Number of targets per label. self._targetCnt = collections.Counter() # Non target scores per label and meta value pattern. self._nonTargetScores = collections.defaultdict(list) # Number of non targets per label. self._nonTargetCnt = collections.Counter() # Target scores per label. self._targetScores4Label = collections.defaultdict(list) self._targetScores4MetaValue = collections.defaultdict(list) # Non target scores per label. self._nonTargetScores4Label = collections.defaultdict(list) self._nonTargetScores4MetaValue = collections.defaultdict(list) self._results = collections.defaultdict(list) # Count which labels + condition exceed the maxNrTargetSamplesPerLabel # and maxNrNonTargetSamplesPerLabel self._targetScoresInExcess = collections.Counter() self._nonTargetScoresInExcess = collections.Counter() self._nrDistinctMetaDataValues = 0 # Contains: { speakerId: metaDataValue } self._metaDataValues = collections.defaultdict(set) self._LabelsToShowAlways = [] self._minimumScore = collections.defaultdict(dict) self._maximumScore = collections.defaultdict(dict) # Keep track of labels. self._targetLabels = set() self._nonTargetLabels = set() # Do we allow both scores (A vs B and B vs A) in a symmetric tests or only the first read? self._allowDups = self.config.getAllowDups() if self.debug: print('Data._source(s):') for el in self._sources: print(el) # If the user did not specify a filename, we assume a database as the source. if self._sources == 'database': print("You need to add some code for this to work!") # And remove the sys.exit(1) statement. #res = self._readFromDatabase() sys.exit(1) else: res = self._readFromFiles(self._sources) # # Choose between decoder for type of results. # if self._dataType == 'type3': self._decodeType3Results(res) elif self._dataType == 'type2': print("Type2 data is not supported anymore. Convert it to type3!") sys.exit(1) elif self._dataType == 'type1': self._decodeType1Results(res) else: print("Unknown data type, must be 'type1' or 'type3'.") sys.exit(1)
def __init__(self): Format.__init__(self, "[:;|]", 2, '''CREATE TABLE data (user text, password text)''', '''INSERT INTO data VALUES (?, ?)''')
# Copyright 2018 Curtis Penner import datetime import getpass import common import constants import log import cmdline import syms from format import Format, Font log = log.log args = cmdline.options() cfmt = Format() PS_LEVEL = 2 def level1_fix(fp): """ Special defs for level 1 Postscript. The fix to define ISOLatin1Encoding for ps level 1 (David Weisman) """ msg = ("/selectfont { exch findfont exch dup %% emulate level 2 op\n" " type /arraytype eq {makefont}{scalefont} ifelse setfont\n" "} bind def\n") # msg_changes = """ /ISOLatin1Encoding