How to use iInputKey method in fMBT

Best Python code snippet using fMBT_python

eyenfinger.py

Source:eyenfinger.py Github

copy

Full Screen

...344def iSetDefaultInputKeyDevice(deviceName):345 """346 Use deviceName as a default input device for iInputKey.347 iSetDefaultInputKeyDevice("/dev/input/event0")348 iInputKey(["enter"])349 """350 global _g_defaultInputKeyDevice351 _g_defaultInputKeyDevice = deviceName352def iSetDefaultReadWithOCR(ocr):353 """354 Set the default for using OCR when reading images or windows.355 """356 global _g_defaultReadWithOCR357 _g_defaultReadWithOCR = ocr358def screenSize():359 """360 Returns the size of the screen as a pair (width, height).361 """362 if _g_screenSize == (0, 0):363 _getScreenSize()364 return _g_screenSize365def windowSize():366 """367 Returns the size of the window as a pair (width, height).368 Choose a window first, for instance with iRead() or iUseWindow().369 """370 if _g_lastWindow == None:371 raise BadWindowName("undefined window")372 return _g_windowSizes[_g_lastWindow]373def windowXY():374 """375 Returns screen coordinates of the top-left corner of the window as376 a pair (x, y).377 Choose a window first, for instance with iRead() or iUseWindow().378 """379 if _g_lastWindow == None:380 raise BadWindowName("undefined window")381 return _g_windowOffsets[_g_lastWindow]382def imageSize(imageFilename):383 """384 Returns image size as pair (width, height).385 """386 struct_bbox = Bbox(0,0,0,0,0)387 err = eye4graphics.imageDimensions(ctypes.byref(struct_bbox),388 imageFilename)389 if err != 0:390 return None, None391 return struct_bbox.right, struct_bbox.bottom392def iRead(windowId = None, source = None, preprocess = None, ocr=None, capture=None, ocrArea=(0, 0, 1.0, 1.0), ocrPageSegModes=(3,)):393 """394 DEPRECATED - use fmbtx11.Screen.refreshScreenshot instead.395 Read the contents of the given window or other source. If neither396 of windowId or source is given, reads the contents of active397 window. iClickWord and iVerifyWord can be used after reading with398 OCR.399 Parameters:400 windowId id (0x....) or the title of the window to be read.401 Defaults to None.402 source name of the file to be read, for instance a screen403 capture. Defaults to None.404 preprocess preprocess specification to override the default405 that is set using setPreprocessFilter. Defaults406 to None. Set to "" to disable preprocessing before407 OCR.408 ocr words will be read using OCR if True409 (the default). Read object can be used with410 iClickIcon and iVerifyIcon without OCR, too.411 capture save image with read words highlighted to this412 file. Default: None (nothing is saved).413 ocrArea (top, left, right, bottom) coordinates -414 area of the image to be read with OCR.415 ocrPageSegModes416 tuple of integers, see tesseract -pagesegmodes417 Returns list of words detected by OCR from the read object.418 """419 global _g_hocr420 global _g_lastWindow421 global _g_words422 global _g_readImage423 global _g_origImage424 _g_words = None425 _g_readImage = None426 _g_origImage = None427 if ocr == None:428 ocr = _g_defaultReadWithOCR429 if not source:430 iUseWindow(windowId)431 # take a screenshot432 _runcmd("xwd -root -screen -out %s.xwd && convert %s.xwd -crop %sx%s+%s+%s +repage '%s'" %433 (SCREENSHOT_FILENAME, SCREENSHOT_FILENAME,434 _g_windowSizes[_g_lastWindow][0], _g_windowSizes[_g_lastWindow][1],435 _g_windowOffsets[_g_lastWindow][0], _g_windowOffsets[_g_lastWindow][1],436 SCREENSHOT_FILENAME))437 source = SCREENSHOT_FILENAME438 else:439 iUseImageAsWindow(source)440 _g_origImage = source441 orig_width, orig_height = _g_windowSizes[_g_lastWindow][0], _g_windowSizes[_g_lastWindow][1]442 x1, y1 = _coordsToInt(ocrArea[:2], (orig_width, orig_height))443 x2, y2 = _coordsToInt(ocrArea[2:], (orig_width, orig_height))444 if x2 <= x1 or y2 <= y1:445 raise EyenfingerError("Invalid area size: %s => %s" % (ocrArea, (x1, y1, x2, y2)))446 if orig_width <= 0 or orig_height <= 0:447 raise EyenfingerError("Invalid image size: %sx%s" % (orig_width, orig_height))448 if not ocr:449 if capture:450 drawWords(_g_origImage, capture, [], [])451 return []452 if preprocess == None:453 preprocess = _g_preprocess454 # convert to text455 _g_readImage = _g_origImage + "-pp.png"456 if ocrArea == (0, 0, 1.0, 1.0):457 croparea = ""458 wordXOffset = 0459 wordYOffset = 0460 else:461 croparea = "-crop %sx%s+%s+%s +repage" % (x2-x1, y2-y1, x1, y1)462 wordXOffset = x1463 wordYOffset = y1464 # rescale possible resize preprocessing parameter465 resize_m = re.search('-resize ([0-9]+)x([0-9]*)', preprocess)466 if resize_m:467 origXResize = int(resize_m.group(1))468 newXResize = int(origXResize/float(orig_width) * (x2-x1))469 preprocess = (preprocess[:resize_m.start()] +470 ("-resize %sx" % (newXResize,)) +471 preprocess[resize_m.end():])472 _g_words = {}473 for psm in ocrPageSegModes:474 cmd = "convert %s %s %s %s && tesseract %s %s -l eng -psm %s hocr" % (475 _g_origImage, croparea, preprocess, _g_readImage,476 _g_readImage, SCREENSHOT_FILENAME, psm)477 _, _g_hocr = _runcmd(cmd)478 hocr_filename = SCREENSHOT_FILENAME + ".html"479 if not os.access(hocr_filename, os.R_OK):480 raise NoOCRResults("HOCR output missing. Tesseract OCR 3.02 or greater required.")481 # store every word and its coordinates482 _g_words.update(_hocr2words(file(hocr_filename).read()))483 # convert word coordinates to the unscaled pixmap484 try:485 ocr_page_line = [line for line in file(hocr_filename).readlines() if "class='ocr_page'" in line][0]486 except IndexError:487 raise NoOCRResults("Could not read ocr_page class information from %s" % (hocr_filename,))488 scaled_width, scaled_height = re.findall('bbox 0 0 ([0-9]+)\s*([0-9]+)', ocr_page_line)[0]489 scaled_width, scaled_height = float(scaled_width) / (float(x2-x1)/orig_width), float(scaled_height) / (float(y2-y1)/orig_height)490 for word in sorted(_g_words.keys()):491 for appearance, (wordid, middle, bbox) in enumerate(_g_words[word]):492 _g_words[word][appearance] = \493 (wordid,494 (int(middle[0]/scaled_width * orig_width) + wordXOffset,495 int(middle[1]/scaled_height * orig_height) + wordYOffset),496 (int(bbox[0]/scaled_width * orig_width) + wordXOffset,497 int(bbox[1]/scaled_height * orig_height) + wordYOffset,498 int(bbox[2]/scaled_width * orig_width) + wordXOffset,499 int(bbox[3]/scaled_height * orig_height) + wordYOffset))500 _log('found "' + word + '": (' + str(bbox[0]) + ', ' + str(bbox[1]) + ')')501 if capture:502 drawWords(_g_origImage, capture, _g_words, _g_words)503 return sorted(_g_words.keys())504def iVerifyWord(word, match=0.33, appearance=1, capture=None):505 """506 DEPRECATED - use fmbtx11.Screen.verifyOcrText instead.507 Verify that word can be found from previously iRead() image.508 Parameters:509 word word that should be checked510 appearance if word appears many times, appearance to511 be clicked. Defaults to the first one.512 match minimum matching score513 capture save image with verified word highlighted514 to this file. Default: None (nothing is saved).515 Returns pair: ((score, matchingWord), (left, top, right, bottom)), where516 score score of found match (1.0 for perfect match)517 matchingWord corresponding word detected by OCR518 (left, top, right, bottom)519 bounding box of the word in read image520 Throws BadMatch error if word is not found.521 Throws NoOCRResults error if there are OCR results available522 on the current screen.523 """524 if _g_words == None:525 raise NoOCRResults('iRead has not been called with ocr=True')526 score, matching_word = findWord(word)527 if capture:528 drawWords(_g_origImage, capture, [word], _g_words)529 if score < match:530 raise BadMatch('No matching word for "%s". The best candidate "%s" with score %.2f, required %.2f' %531 (word, matching_word, score, match))532 return ((score, matching_word), _g_words[matching_word][appearance-1][2])533def iVerifyText(text, match=0.33, capture=None):534 """535 DEPRECATED - use fmbtx11.Screen.verifyOcrText instead.536 Verify that text can be found from previously iRead() image.537 Parameters:538 text multiple words that should be checked539 match minimum matching score540 capture save image with verified text highlighted541 to this file. Default: None (nothing is saved).542 Returns pair:543 ((score, matchingText), (left, top, right, bottom)), where544 score score of found match (1.0 for perfect match)545 matchingText corresponding text detected by OCR546 (left, top, right, bottom)547 bounding box of the text in read image548 Throws BadMatch error if text is not found.549 Throws NoOCRResults error if there are OCR results available550 on the current screen.551 """552 if _g_words == None:553 raise NoOCRResults('iRead has not been called with ocr=True')554 score_text_bbox_list = findText(text, match)555 if len(score_text_bbox_list) == 0:556 raise BadMatch('No match >= %s for text "%s"' % (score, text))557 score, text, bbox = score_text_box_list[0]558 if capture:559 drawBbox(_g_origImage, capture, bbox, "%.2f %s" % (score, text))560 return ((score, matching_text), bbox)561def iVerifyIcon(iconFilename, match=None, colorMatch=None, opacityLimit=None, capture=None, area=(0.0, 0.0, 1.0, 1.0), _origin="iVerifyIcon"):562 """563 DEPRECATED - use fmbtx11.Screen.verifyBitmap instead.564 Verify that icon can be found from previously iRead() image.565 Parameters:566 iconFilename name of the icon file to be searched for567 match minimum matching score between 0 and 1.0,568 1.0 is perfect match (default)569 colorMatch 1.0 (default) requires exact color match. Value570 below 1.0 defines maximum allowed color571 difference. See iSetDefaultIconColorMatch.572 opacityLimit 0.0 (default) requires exact color values573 independently of opacity. If lower than 1.0,574 pixel less opaque than given value are skipped575 in pixel perfect comparisons.576 capture save image with verified icon highlighted577 to this file. Default: None (nothing is saved).578 area rectangle (left, top, right, bottom). Search579 icon inside this rectangle only. Values can be580 absolute coordinates, or floats in range [0.0,581 1.0] that will be scaled to image dimensions.582 The default is (0.0, 0.0, 1.0, 1.0), that is583 full rectangle.584 Returns pair: (score, (left, top, right, bottom)), where585 score score of found match (1.0 for perfect match)586 (left, top, right, bottom)587 bounding box of found icon588 Throws BadMatch error if icon is not found.589 """590 if not eye4graphics:591 _log('ERROR: %s("%s") called, but eye4graphics not loaded.' % (_origin, iconFilename))592 raise EyenfingerError("eye4graphics not available")593 if not _g_origImage:594 _log('ERROR %s("%s") called, but source not defined (iRead not called).' % (_origin, iconFilename))595 raise BadSourceImage("Source image not defined, cannot search for an icon.")596 if not (os.path.isfile(iconFilename) and os.access(iconFilename, os.R_OK)):597 _log('ERROR %s("%s") called, but the icon file is not readable.' % (_origin, iconFilename))598 raise BadIconImage('Icon "%s" is not readable.' % (iconFilename,))599 if match == None:600 match = _g_defaultIconMatch601 if match > 1.0:602 _log('ERROR %s("%s"): invalid match value, must be below 1.0. ' % (_origin, iconFilename,))603 raise ValueError("invalid match value: %s, should be 0 <= match <= 1.0" % (match,))604 if colorMatch == None:605 colorMatch = _g_defaultIconColorMatch606 if not 0.0 <= colorMatch <= 1.0:607 _log('ERROR %s("%s"): invalid colorMatch value, must be between 0 and 1. ' % (_origin, iconFilename,))608 raise ValueError("invalid colorMatch value: %s, should be 0 <= colorMatch <= 1.0" % (colorMatch,))609 if opacityLimit == None:610 opacityLimit = _g_defaultIconOpacityLimit611 if not 0.0 <= opacityLimit <= 1.0:612 _log('ERROR %s("%s"): invalid opacityLimit value, must be between 0 and 1. ' % (_origin, iconFilename,))613 raise ValueError("invalid opacityLimit value: %s, should be 0 <= opacityLimit <= 1.0" % (opacityLimit,))614 if area[0] > area[2] or area[1] >= area[3]:615 raise ValueError("invalid area: %s, should be rectangle (left, top, right, bottom)" % (area,))616 leftTopRightBottomZero = (_coordsToInt((area[0], area[1]), windowSize()) +617 _coordsToInt((area[2], area[3]), windowSize()) +618 (0,))619 struct_area_bbox = Bbox(*leftTopRightBottomZero)620 struct_bbox = Bbox(0,0,0,0,0)621 threshold = int((1.0-match)*20)622 err = eye4graphics.findSingleIcon(ctypes.byref(struct_bbox),623 _g_origImage, iconFilename, threshold,624 ctypes.c_double(colorMatch),625 ctypes.c_double(opacityLimit),626 ctypes.byref(struct_area_bbox))627 bbox = (int(struct_bbox.left), int(struct_bbox.top),628 int(struct_bbox.right), int(struct_bbox.bottom))629 if err == -1 or err == -2:630 msg = '%s: "%s" not found, match=%.2f, threshold=%s, closest threshold %s.' % (631 _origin, iconFilename, match, threshold, int(struct_bbox.error))632 if capture:633 drawIcon(_g_origImage, capture, iconFilename, bbox, 'red')634 _log(msg)635 raise BadMatch(msg)636 elif err != 0:637 _log("%s: findSingleIcon returned %s" % (_origin, err,))638 raise BadMatch("%s not found, findSingleIcon returned %s." % (iconFilename, err))639 if threshold > 0:640 score = (threshold - int(struct_bbox.error)) / float(threshold)641 else:642 score = 1.0643 if capture:644 drawIcon(_g_origImage, capture, iconFilename, bbox, area=leftTopRightBottomZero[:4])645 return (score, bbox)646def iClickIcon(iconFilename, clickPos=(0.5,0.5), match=None,647 colorMatch=None, opacityLimit=None,648 mouseButton=1, mouseEvent=MOUSEEVENT_CLICK, dryRun=None, capture=None):649 """650 DEPRECATED - use fmbtx11.Screen.tapBitmap instead.651 Click coordinates relative to the given icon in previously iRead() image.652 Parameters:653 iconFilename read icon from this file654 clickPos position to be clicked,655 relative to word top-left corner of the bounding656 box around the word. X and Y units are relative657 to width and height of the box. (0,0) is the658 top-left corner, (1,1) is bottom-right corner,659 (0.5, 0.5) is the middle point (default).660 Values below 0 or greater than 1 click outside661 the bounding box.662 match 1.0 (default) requires exact match. Value below 1.0663 defines minimum required score for fuzzy matching664 (EXPERIMENTAL). See iSetDefaultIconMatch.665 colorMatch 1.0 (default) requires exact color match. Value666 below 1.0 defines maximum allowed color667 difference. See iSetDefaultIconColorMatch.668 opacityLimit 0.0 (default) requires exact color values669 independently of opacity. If lower than 1.0,670 pixel less opaque than given value are skipped671 in pixel perfect comparisons.672 mouseButton mouse button to be synthesized on the event, default is 1.673 mouseEvent event to be synthesized, the default is MOUSEEVENT_CLICK,674 others: MOUSEEVENT_MOVE, MOUSEEVENT_DOWN, MOUSEEVENT_UP.675 dryRun if True, does not synthesize events. Still returns676 coordinates of the clicked position and illustrates677 the clicked position on the capture image if678 given.679 capture name of file where image of highlighted icon and680 clicked point are saved.681 Returns pair (score, (clickedX, clickedY)), where682 score score of found match (1.0 for perfect match)683 (clickedX, clickedY)684 X and Y coordinates of clicked position on the685 screen.686 Throws BadMatch error if could not find a matching word.687 """688 _DEPRECATED()689 score, bbox = iVerifyIcon(iconFilename, match=match,690 colorMatch=colorMatch, opacityLimit=opacityLimit,691 capture=capture, _origin="iClickIcon")692 clickedXY = iClickBox(bbox, clickPos, mouseButton, mouseEvent, dryRun,693 capture, _captureText = iconFilename)694 return (score, clickedXY)695def iClickWord(word, appearance=1, clickPos=(0.5,0.5), match=0.33,696 mouseButton=1, mouseEvent=1, dryRun=None, capture=None):697 """698 DEPRECATED - use fmbtx11.Screen.tapOcrText instead.699 Click coordinates relative to the given word in previously iRead() image.700 Parameters:701 word word that should be clicked702 appearance if word appears many times, appearance to703 be clicked. Defaults to the first one.704 clickPos position to be clicked,705 relative to word top-left corner of the bounding706 box around the word. X and Y units are relative707 to width and height of the box. (0,0) is the708 top-left corner, (1,1) is bottom-right corner,709 (0.5, 0.5) is the middle point (default).710 Values below 0 or greater than 1 click outside711 the bounding box.712 capture name of file where image of highlighted word and713 clicked point are saved.714 Returns pair: ((score, matchingWord), (clickedX, clickedY)), where715 score score of found match (1.0 for perfect match)716 matchingWord corresponding word detected by OCR717 (clickedX, clickedY)718 X and Y coordinates of clicked position on the719 screen.720 Throws BadMatch error if could not find a matching word.721 Throws NoOCRResults error if there are OCR results available722 on the current screen.723 """724 _DEPRECATED()725 (score, matching_word), bbox = iVerifyWord(word, appearance=appearance, match=match, capture=False)726 clickedX, clickedY = iClickBox(bbox, clickPos, mouseButton, mouseEvent, dryRun, capture=False)727 windowId = _g_lastWindow728 _log('iClickWord("%s"): word "%s", match %.2f, bbox %s, window offset %s, click %s' %729 (word, matching_word, score,730 bbox, _g_windowOffsets[windowId],731 (clickedX, clickedY)))732 if capture:733 drawWords(_g_origImage, capture, [word], _g_words)734 drawClickedPoint(capture, capture, (clickedX, clickedY))735 return ((score, matching_word), (clickedX, clickedY))736def iClickBox((left, top, right, bottom), clickPos=(0.5, 0.5),737 mouseButton=1, mouseEvent=1, dryRun=None,738 capture=None, _captureText=None):739 """740 DEPRECATED - use fmbtx11.Screen.tapItem instead.741 Click coordinates relative to the given bounding box, default is742 in the middle of the box.743 Parameters:744 (left, top, right, bottom)745 coordinates of the box inside the window.746 (0, 0) is the top-left corner of the window.747 clickPos (offsetX, offsetY) position to be clicked,748 relative to the given box. (0, 0) is the749 top-left, and (1.0, 1.0) is the lower-right750 corner of the box. The default is (0.5, 0.5),751 that is, the middle point of the box. Values752 smaller than 0 and bigger than 1 are allowed,753 too.754 mouseButton mouse button to be synthesized on the event, default is 1.755 mouseEvent event to be synthesized, the default is MOUSEEVENT_CLICK,756 others: MOUSEEVENT_MOVE, MOUSEEVENT_DOWN, MOUSEEVENT_UP.757 dryRun if True, does not synthesize events. Still returns758 coordinates of the clicked position and illustrates759 the clicked position on the capture image if760 given.761 capture name of file where the last screenshot with762 clicked point highlighted is saved. The default763 is None (nothing is saved).764 Returns pair (clickedX, clickedY)765 X and Y coordinates of clicked position on the766 screen.767 """768 clickWinX = int(left + clickPos[0]*(right-left))769 clickWinY = int(top + clickPos[1]*(bottom-top))770 (clickedX, clickedY) = iClickWindow((clickWinX, clickWinY),771 mouseButton, mouseEvent,772 dryRun, capture=False)773 if capture:774 if _captureText == None:775 _captureText = "Box: %s, %s, %s, %s" % (left, top, right, bottom)776 drawIcon(_g_origImage, capture, _captureText, (left, top, right, bottom))777 drawClickedPoint(capture, capture, (clickedX, clickedY))778 return (clickedX, clickedY)779def iClickWindow((clickX, clickY), mouseButton=1, mouseEvent=1, dryRun=None, capture=None):780 """781 DEPRECATED - use fmbtx11.Screen.tap instead.782 Click given coordinates in the window.783 Parameters:784 (clickX, clickY)785 coordinates to be clicked inside the window.786 (0, 0) is the top-left corner of the window.787 Integer values are window coordinates. Floating788 point values from 0.0 to 1.0 are scaled to window789 coordinates: (0.5, 0.5) is the middle of the790 window, and (1.0, 1.0) the bottom-right corner of791 the window.792 mouseButton mouse button to be synthesized on the event, default is 1.793 mouseEvent event to be synthesized, the default is MOUSEEVENT_CLICK,794 others: MOUSEEVENT_MOVE, MOUSEEVENT_DOWN, MOUSEEVENT_UP.795 dryRun if True, does not synthesize events. Still796 illustrates the clicked position on the capture797 image if given.798 capture name of file where the last screenshot with799 clicked point highlighted is saved. The default800 is None (nothing is saved).801 Returns pair (clickedX, clickedY)802 X and Y coordinates of clicked position on the803 screen.804 """805 # Get the size of the window806 wndSize = windowSize()807 (clickX, clickY) = _coordsToInt((clickX, clickY), wndSize)808 # Get the position of the window809 wndPos = windowXY()810 # If coordinates are given as percentages, convert to window coordinates811 clickScrX = clickX + wndPos[0]812 clickScrY = clickY + wndPos[1]813 iClickScreen((clickScrX, clickScrY), mouseButton, mouseEvent, dryRun, capture)814 return (clickScrX, clickScrY)815def iClickScreen((clickX, clickY), mouseButton=1, mouseEvent=1, dryRun=None, capture=None):816 """817 DEPRECATED - use fmbtx11.Screen.tap instead.818 Click given absolute coordinates on the screen.819 Parameters:820 (clickX, clickY)821 coordinates to be clicked on the screen. (0, 0)822 is the top-left corner of the screen. Integer823 values are screen coordinates. Floating point824 values from 0.0 to 1.0 are scaled to screen825 coordinates: (0.5, 0.5) is the middle of the826 screen, and (1.0, 1.0) the bottom-right corner of827 the screen.828 mouseButton mouse button to be synthesized on the event, default is 1.829 mouseEvent event to be synthesized, the default is MOUSEEVENT_CLICK,830 others: MOUSEEVENT_MOVE, MOUSEEVENT_DOWN, MOUSEEVENT_UP.831 dryRun if True, does not synthesize events. Still832 illustrates the clicked position on the capture833 image if given.834 capture name of file where the last screenshot with835 clicked point highlighted is saved. The default836 is None (nothing is saved).837 """838 _DEPRECATED()839 if mouseEvent == MOUSEEVENT_CLICK:840 params = "'mouseclick %s'" % (mouseButton,)841 elif mouseEvent == MOUSEEVENT_DOWN:842 params = "'mousedown %s'" % (mouseButton,)843 elif mouseEvent == MOUSEEVENT_UP:844 params = "'mouseup %s'" % (mouseButton,)845 else:846 params = ""847 clickX, clickY = _coordsToInt((clickX, clickY))848 if capture:849 drawClickedPoint(_g_origImage, capture, (clickX, clickY))850 if dryRun == None:851 dryRun = _g_defaultClickDryRun852 if not dryRun:853 # use xte from the xautomation package854 _runcmd("xte 'mousemove %s %s' %s" % (clickX, clickY, params))855def iGestureScreen(listOfCoordinates, duration=0.5, holdBeforeGesture=0.0, holdAfterGesture=0.0, intermediatePoints=0, capture=None, dryRun=None):856 """857 DEPRECATED - use fmbtx11.Screen.drag instead.858 Synthesizes a gesture on the screen.859 Parameters:860 listOfCoordinates861 The coordinates through which the cursor moves.862 Integer values are screen coordinates. Floating863 point values from 0.0 to 1.0 are scaled to screen864 coordinates: (0.5, 0.5) is the middle of the865 screen, and (1.0, 1.0) the bottom-right corner of866 the screen.867 duration gesture time in seconds, excluding868 holdBeforeGesture and holdAfterGesture times.869 holdBeforeGesture870 time in seconds to keep mouse down before the871 gesture.872 holdAfterGesture873 time in seconds to keep mouse down after the874 gesture.875 intermediatePoints876 the number of intermediate points to be added877 between each of the coordinates. Intermediate878 points are added to straight lines between start879 and end points.880 capture name of file where the last screenshot with881 the points through which the cursors passes is882 saved. The default is None (nothing is saved).883 dryRun if True, does not synthesize events. Still884 illustrates the coordinates through which the cursor885 goes.886 """887 _DEPRECATED()888 # The params list to be fed to xte889 params = []890 # The list of coordinates through which the cursor has to go891 goThroughCoordinates = []892 for pos in xrange(len(listOfCoordinates)):893 x, y = _coordsToInt(listOfCoordinates[pos])894 goThroughCoordinates.append((x,y))895 if pos == len(listOfCoordinates) - 1:896 break # last coordinate added897 nextX, nextY = _coordsToInt(listOfCoordinates[pos+1])898 (x,y), (nextX, nextY) = (x, y), (nextX, nextY)899 for ip in range(intermediatePoints):900 goThroughCoordinates.append(901 (int(round(x + (nextX-x)*(ip+1)/float(intermediatePoints+1))),902 int(round(y + (nextY-y)*(ip+1)/float(intermediatePoints+1)))))903 # Calculate the time (in micro seconds) to sleep between moves.904 if len(goThroughCoordinates) > 1:905 moveDelay = 1000000 * float(duration) / (len(goThroughCoordinates)-1)906 else:907 moveDelay = 0908 if not dryRun:909 # Build the params list.910 params.append("'mousemove %d %d'" % goThroughCoordinates[0])911 params.append("'mousedown 1 '")912 if holdBeforeGesture > 0:913 params.append("'usleep %d'" % (holdBeforeGesture * 1000000,))914 for i in xrange(1, len(goThroughCoordinates)):915 params.append("'usleep %d'" % (moveDelay,))916 params.append("'mousemove %d %d'" % goThroughCoordinates[i])917 if holdAfterGesture > 0:918 params.append("'usleep %d'" % (holdAfterGesture * 1000000,))919 params.append("'mouseup 1'")920 # Perform the gesture921 _runcmd("xte %s" % (" ".join(params),))922 if capture:923 intCoordinates = [ _coordsToInt(point) for point in listOfCoordinates ]924 drawLines(_g_origImage, capture, intCoordinates, goThroughCoordinates)925 return goThroughCoordinates926def iGestureWindow(listOfCoordinates, duration=0.5, holdBeforeGesture=0.0, holdAfterGesture=0.0, intermediatePoints=0, capture=None, dryRun=None):927 """928 DEPRECATED - use fmbtx11.Screen.drag instead.929 Synthesizes a gesture on the window.930 Parameters:931 listOfCoordinates932 The coordinates through which the cursor moves.933 Integer values are window coordinates. Floating934 point values from 0.0 to 1.0 are scaled to window935 coordinates: (0.5, 0.5) is the middle of the936 window, and (1.0, 1.0) the bottom-right corner of937 the window.938 duration gesture time in seconds, excluding939 holdBeforeGesture and holdAfterGesture times.940 holdBeforeGesture941 time in seconds to keep mouse down before the942 gesture.943 holdAfterGesture944 time in seconds to keep mouse down after the945 gesture.946 intermediatePoints947 the number of intermediate points to be added948 between each of the coordinates. Intermediate949 points are added to straight lines between start950 and end points.951 capture name of file where the last screenshot with952 the points through which the cursors passes is953 saved. The default is None (nothing is saved).954 dryRun if True, does not synthesize events. Still955 illustrates the coordinates through which the cursor956 goes.957 """958 screenCoordinates = [ _windowToScreen(*_coordsToInt((x,y),windowSize())) for (x,y) in listOfCoordinates ]959 return iGestureScreen(screenCoordinates, duration, holdBeforeGesture, holdAfterGesture, intermediatePoints, capture, dryRun)960def iType(word, delay=0.0):961 """962 DEPRECATED - use fmbtx11.Screen.type instead.963 Send keypress events.964 Parameters:965 word is either966 - a string containing letters and numbers.967 Each letter/number is using press and release events.968 - a list that contains969 - keys: each key is sent using press and release events.970 - (key, event)-pairs: the event (either "press" or "release")971 is sent.972 - (key1, key2, ..., keyn)-tuples. 2n events is sent:973 key1 press, key2 press, ..., keyn press,974 keyn release, ..., key2 release, key1 release.975 Keys are defined in eyenfinger.Xkeys, for complete list976 see keysymdef.h.977 delay is given as seconds between sent events978 Examples:979 iType('hello')980 iType([('Shift_L', 'press'), 'h', 'e', ('Shift_L', 'release'), 'l', 'l', 'o'])981 iType([('Control_L', 'Alt_L', 'Delete')])982 """983 _DEPRECATED()984 args = []985 for char in word:986 if type(char) == tuple:987 if char[1].lower() == 'press':988 args.append("'keydown %s'" % (char[0],))989 elif char[1].lower() == 'release':990 args.append("'keyup %s'" % (char[0],))991 else:992 rest = []993 for key in char:994 args.append("'keydown %s'" % (key,))995 rest.insert(0, "'keyup %s'" % (key,))996 args = args + rest997 else:998 # char is keyname or single letter/number999 args.append("'key %s'" % (char,))1000 usdelay = " 'usleep %s' " % (int(delay*1000000),)1001 _runcmd("xte %s" % (usdelay.join(args),))1002def iInputKey(*args, **kwargs):1003 """1004 DEPRECATED - use fmbtx11.Screen.pressKey instead.1005 Send keypresses using Linux evdev interface1006 (/dev/input/eventXX).1007 iInputKey(keySpec[, keySpec...], hold=<float>, delay=<float>, device=<str>)1008 Parameters:1009 keySpec is one of the following:1010 - a string of one-character-long key names:1011 "aesc" will send four keypresses: A, E, S and C.1012 - a list of key names:1013 ["a", "esc"] will send two keypresses: A and ESC.1014 Key names are listed in eyenfinger.InputKeys.1015 - an integer:1016 116 will press the POWER key.1017 - "_" or "^":1018 only press or release event will be generated1019 for the next key, respectively.1020 If a key name inside keySpec is prefixed by "_"1021 or "^", only press or release event is generated...

Full Screen

Full Screen

FuzzyTools.py

Source:FuzzyTools.py Github

copy

Full Screen

1#------------------------------------------------------------------#2#******************************************************************#3# Fuzzy Base CLASSES: FuzzyTools.py #4#******************************************************************#5#------------------------------------------------------------------#6# Ersteller: Markus Schatz #7# Mail: schatz@llb.mw.tum.de #8#------------------------------------------------------------------#9# Change-Log: #10# 2015-02-02 Definition of class: #11# o First definition of class #12#------------------------------------------------------------------#13#------------------------------------------------------------------#14# Included classes are: #15# o FIS #16# - Class for creating a FIS object #17# o MembershipFunction #18# - Class for handling membership functions #19# o FuzzyTools #20# - Class for fuzzification, Rule eval and defuzzification #21# o Pimf #22# o Zmf #23# o Trimf #24# o Smf #25# o Const #26# o Gaussmf #27# o Gauss2mf #28#------------------------------------------------------------------#29#------------------------------------------------------------------#3031# Imports32#------------------------------------------------------------------#33import numpy as np34import copy as cp35import math36import sys3738# Definition of orthogonal projection39#------------------------------------------------------------------#40def orthogonal_proj(zfront, zback):41 a = (zfront+zback)/(zfront-zback)42 b = -2*(zfront*zback)/(zfront-zback)43 return np.array([[1,0,0,0],44 [0,1,0,0],45 [0,0,a,b],46 [0,0,-0.0001,zback]])4748# Global function definitions49#------------------------------------------------------------------#50def SurfacePlotter(fig,ax,X,Y,Z,SubTitel,xLabel,yLabel, AlphaVal=1.):51 try:52 from matplotlib import cm53 from mpl_toolkits.mplot3d import proj3d54 except:55 logging.error('Matplotlib could not be imported!')56 surf = ax.plot_surface(X, Y, Z, alpha = AlphaVal, rstride=1, cstride=1, cmap=cm.coolwarm,57 linewidth=0, antialiased=False)58 proj3d.persp_transformation = orthogonal_proj59 #ax.set_zlim(-1.01, 1.01)60 #ax.zaxis.set_major_locator(LinearLocator(10))61 #ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))62 cbar = fig.colorbar(surf, shrink=0.5, aspect=5)63 cbar.ax.tick_params(labelsize=20)64 if SubTitel:65 ax.set_title(SubTitel, fontsize=22)66 if xLabel:67 ax.set_xlabel(xLabel, fontsize=22)68 if yLabel:69 ax.set_ylabel(yLabel, fontsize=22)70def smfFCT(x,Para,Parb):71 if Para >= Parb:72 smf = int(x >= (Para+Parb)/2.0)73 else:74 smf = 0.075 if (x <= Para):76 smf = 0.077 if ((Para < x) & (x <= (Para+Parb)/2.0)):78 smf = 2.0*((x-Para)/(Parb-Para))**279 if (((Para+Parb)/2.0 < x) & (x <= Parb)):80 smf = 1.0-2.0*((x-Parb)/(Parb-Para))**281 if (Parb <= x):82 smf = 1.083 return smf84def zmfFCT(x,Parc,Pard):85 if Parc >= Pard:86 zmf = int(x <= (Pard+Parc)/2.0)87 else:88 zmf = 0.089 if x <= Parc:90 zmf = 1.091 if ((Parc < x) & (x <= (Parc+Pard)/2)):92 zmf = 1.0-2.0*((x-Parc)/(Parc-Pard))**293 if (((Parc+Pard)/2.0 < x) & (x <= Pard)):94 zmf = 2.0*((Pard-x)/(Parc-Pard))**295 if (Pard <= x):96 zmf = 0.097 return zmf9899# Base class definition100#------------------------------------------------------------------#101class MembershipFunction(object): # Base class for all membership functions102 NumInfiSlice = 1e3103 def __init__(self):104 pass105 def CompArea(self,xL,xU,Ful):106 Area = 0.0107 xSample = np.linspace(xL,xU,num=self.NumInfiSlice)108 for ixSample in range(1,np.size(xSample)):109 xP=xSample[ixSample-1]110 xN=xSample[ixSample]111 yP=self(xP)112 if yP>Ful:113 yP=Ful114 yN=self(xN)115 if yN>Ful:116 yN=Ful117 Area+=(xN-xP)*(yN+yP)*.5118 return Area119 def CompCoA(self,xL,xU,Ful):120 Area = 0.0121 CoG = 0.0122 xSample = np.linspace(xL,xU,num=self.NumInfiSlice)123 for ixSample in range(1,np.size(xSample)):124 xP=xSample[ixSample-1]125 xN=xSample[ixSample]126 yP=self(xP)127 if yP>Ful:128 yP=Ful129 yN=self(xN)130 if yN>Ful:131 yN=Ful132 Area+=(xN-xP)*(yN+yP)*.5133 CoG+=(xN-xP)*(yN+yP)*.5*((xN-xP)*.5+xP)134 return CoG/Area135136class Gauss2mf(MembershipFunction):137 def __init__(self,Sig1, c1, Sig2, c2):138 self.Sig1 = Sig1+0.0139 self.c1 = c1+0.0140 self.Sig2 = Sig2+0.0141 self.c2 = c2+0.0142 def __call__(self,x):143 c1i = (x<=self.c1)144 c2i = (x>=self.c2)145 y1 = math.exp(-(x-self.c1)**2/(2.0*self.Sig1**2))*c1i+(1-c1i)146 y2 = math.exp(-(x-self.c2)**2/(2.0*self.Sig2**2))*c2i+(1-c2i)147 return y1*y2148 def __str__(self):149 return 'Combined gaussian mf'150151class Gaussmf(MembershipFunction):152 def __init__(self,Sig, c):153 self.Sig = Sig+0.0154 self.c = c+0.0155 def __call__(self,x):156 return math.exp(-(x-self.c)**2/(2.0*self.Sig**2))157 def __str__(self):158 return 'Gaussian mf'159160class Const(MembershipFunction):161 def __init__(self, c):162 self.c = c+0.0163 def __call__(self,x):164 return self.c165 def __str__(self):166 return 'Constant mf'167168class Smf(MembershipFunction):169 def __init__(self,a,b):170 self.a = a+0.0171 self.b = b+0.0172 def __call__(self,x):173 return smfFCT(x,self.a,self.b)174 def __str__(self):175 return 'S-shaped mf'176177class Trimf(MembershipFunction):178 def __init__(self,a,b,c):179 self.a = a+0.0180 self.b = b+0.0181 self.c = c+0.0182 def __call__(self,x):183 if (x<=self.a or self.c<=x):184 return 0.0185 if self.a!=self.b:186 if self.a<x and x<self.b:187 return (x-self.a)/(self.b-self.a)188 if self.b!=self.c:189 if self.b<x and x<self.c:190 return (self.c-x)/(self.c-self.b)191 if x==self.b:192 return 1.0193 def __str__(self):194 return 'S-shaped mf'195196class Zmf(MembershipFunction):197 def __init__(self,c,d):198 self.c = c+0.0199 self.d = d+0.0200 def __call__(self,x):201 return zmfFCT(x,self.c,self.d)202 def __str__(self):203 return 'Z-shaped mf'204205class Pimf(MembershipFunction):206 def __init__(self,a,b,c,d):207 self.a = a+0.0208 self.b = b+0.0209 self.c = c+0.0210 self.d = d+0.0211 def __call__(self,x):212 return smfFCT(x,self.a,self.b)*zmfFCT(x,self.c,self.d)213 def __str__(self):214 return 'Pi-shaped mf'215216class FuzzyTools(object): # Base class for all fuzzy tools217 NumInfiSlice = 1e3218 def __init__(self,Name,Type,InfoUpperStr):219 self.Name = Name220 self.Type = Type221 self.InfoStr = ''222 self.InfoUpperStr = InfoUpperStr223 def WriteInfo(self):224 self.InfoStr = 'Name \t: '+self.Name+'\nType \t: '+self.Type+'\n'225 if not self.Input:226 self.InfoStr = self.InfoStr+'No inputs yet!\n'227 else:228 self.ResetInput()229 self.InfoStr = self.InfoStr+'NumInputs \t: '+str(self.nInpRules)+'\n'230 if not self.Output:231 self.InfoStr = self.InfoStr+'No outputs yet!\n'232 else:233 self.ResetOutput()234 self.InfoStr = self.InfoStr+'NumOutputs \t: '+str(self.nOutRules)+'\n'235 if not self.Rules:236 self.InfoStr = self.InfoStr+'No outputs yet!\n'237 else:238 for iRule in self.Rules.keys():239 InpStr = 'If '240 for iStr in range(self.nInpRules):241 if iStr>0:242 InpStr = InpStr+' '+self.Rules[iRule][0]+' '243 InpStr = InpStr + self.Rules[iRule][iStr*2+1]+' '+self.Rules[iRule][iStr*2+2]244 self.InfoStr = self.InfoStr+'Rule '+iRule+': ('+self.Rules[iRule][0]+') '+InpStr+' '+self.Rules[iRule][self.nInpRules*2+1]+' '+self.Rules[iRule][self.nInpRules*2+2]+' '+self.Rules[iRule][self.nInpRules*2+3]+'\n'245 self.InfoStr = self.InfoStr+self.InfoUpperStr246 def ResetInput(self):247 self.nInpRules = len(self.Input.keys())248 def ResetOutput(self):249 self.nOutRules = len(self.Output.keys())250 def ResetRules(self):251 self.nRules = len(self.Rules.keys())252 def Prod(self,List):253 Prod = 1254 for i in List:255 Prod *= i256 return Prod257 def Sum(self,List):258 Sum = 0259 for i in List:260 Sum += i261 return Sum262 def AND(self,InputVals):263 if self.AndMethod == 'min':264 return min(InputVals)265 elif self.AndMethod == 'prod':266 return self.Prod(InputVals)267 else:268 if self.PrintInfo:269 print('Desired AND-Rule not implemented yet!')270 return []271 def OR(self,InputVals):272 if self.OrMethod == 'max':273 return max(InputVals)274 elif self.OrMethod == 'sum':275 return self.Sum(InputVals)276 else:277 if self.PrintInfo:278 print('Desired OR-Rule not implemented yet!')279 return []280 def Fuzzify(self,InputDict):281 self.InputFuzzyVals = dict()282 for iInput in self.Input.keys():283 self.InputFuzzyVals[iInput] = dict()284 for iMF in self.Input[iInput]['MF'].keys():285 self.InputFuzzyVals[iInput][iMF] = self.Input[iInput]['MF'][iMF](InputDict[iInput])286 def EvalImpl(self,CurRule):287 InpVals=[]288 for iInput in range(self.nInpRules):289 InpVals.append(self.InputFuzzyVals[CurRule[iInput*2+1]][CurRule[iInput*2+2]])290 self.InpValsTMP = cp.deepcopy(InpVals)291 if CurRule[0]=='AND':292 ImpVal = self.AND(InpVals)293 elif CurRule[0]=='OR':294 ImpVal = self.OR(InpVals)295 else:296 if self.PrintInfo:297 print('Desired rule not implemented yet!')298 return []299 return ImpVal300 def Defuzzify(self,ImpVal):301 Area = 0.0302 CoG = 0.0303 #iKey = self.Output.keys()[0]304 iKey = list(self.Output)[0]305 xSample = np.linspace(self.Output[iKey]['Range'][0],self.Output[iKey]['Range'][1],num=self.NumInfiSlice)306 for ixSample in range(1,np.size(xSample)):307 xP=xSample[ixSample-1]308 xN=xSample[ixSample]309 if self.AggRule=='sum':310 yP=0311 yN=0312 iR=0313 for iRule in self.Rules.keys():314 yTMP=self.Output[self.Rules[iRule][self.nInpRules*2+2]]['MF'][self.Rules[iRule][self.nInpRules*2+3]](xP)315 if self.ImpRule=='min':316 if yTMP>ImpVal[iR]:317 yP+=ImpVal[iR]318 else:319 yP+=yTMP320 elif self.ImpRule=='prod':321 yP+=yTMP*ImpVal[iR]322 yTMP=self.Output[self.Rules[iRule][self.nInpRules*2+2]]['MF'][self.Rules[iRule][self.nInpRules*2+3]](xN)323 if self.ImpRule=='min':324 if yTMP>ImpVal[iR]:325 yN+=ImpVal[iR]326 else:327 yN+=yTMP328 elif self.ImpRule=='prod':329 yN+=yTMP*ImpVal[iR]330 iR+=1331 elif self.AggRule=='max':332 yPL=[]333 yNL=[]334 iR=0335 for iRule in self.Rules.keys():336 yTMP=self.Output[self.Rules[iRule][self.nInpRules*2+2]]['MF'][self.Rules[iRule][self.nInpRules*2+3]](xP)337 if self.ImpRule=='min':338 if yTMP>ImpVal[iR]:339 yPL.append(ImpVal[iR])340 else:341 yPL.append(yTMP)342 elif self.ImpRule=='prod':343 yPL.append(yTMP*ImpVal[iR])344 yTMP=self.Output[self.Rules[iRule][self.nInpRules*2+2]]['MF'][self.Rules[iRule][self.nInpRules*2+3]](xN)345 if self.ImpRule=='min':346 if yTMP>ImpVal[iR]:347 yNL.append(ImpVal[iR])348 else:349 yNL.append(yTMP)350 elif self.ImpRule=='prod':351 yNL.append(yTMP*ImpVal[iR])352 iR+=1353 yP=max(yPL)354 yN=max(yNL)355 else:356 if self.PrintInfo:357 print('Desired Agg-Rule not implemented yet!')358 return []359 Area+=(xN-xP)*(yN+yP)*.5360 CoG+=(xN-xP)*(yN+yP)*.5*((xN-xP)*.5+xP)361 return CoG/Area362363class FIS(FuzzyTools):364 Input = dict()365 Output = dict()366 Rules = dict()367 def __init__(self,FISname,PrintInfo=False,AndMethod='prod',OrMethod='max',ImpRule='min',AggRule='sum',DefuzzMethod='CoA'):368 # Alternatives are AndMethod='prod/min',OrMethod='max/sum',ImpRule='prod',AggRule='max/sum',DefuzzMethod='CoA'369 InfoStr = 'AndMethod \t: '+AndMethod+'\nOrMethod \t: '+OrMethod+'\nImpRule \t:'+ImpRule+'\nAggRule \t:'+AggRule+'\nDefuzzMethod \t:'+DefuzzMethod+'\n'370 FuzzyTools.__init__(self,FISname,'Mandani',InfoStr)371 self.FISname = FISname372 self.AndMethod = AndMethod373 self.OrMethod = OrMethod374 self.ImpRule = ImpRule375 self.AggRule = AggRule376 self.PrintInfo = PrintInfo377 def __str__(self):378 self.WriteInfo()379 return '-###############-\n-# Mandani-FIS #-\n-###############-\n'+self.InfoStr380 def GetOutputImplicationVals(self,InputDict):381 self.EvalFIS(InputDict)382 return self.OutImpl383 def EvalFIS(self,InputDict):384 #x=np.array(x)385 self.ResetInput()386 self.ResetOutput()387 self.ResetRules()388 #if len(InputDict.keys())!=self.nInpRules:389 # if self.PrintInfo:390 # print 'Length of X differs from number of existing input rules!'391 # return []392 self.Fuzzify(InputDict)393 self.OutImpl = []394 self.InpPerRuleVals=dict()395 for iRule in self.Rules.keys():396 self.OutImpl.append(self.EvalImpl(self.Rules[iRule]))397 self.InpPerRuleVals[iRule] = self.InpValsTMP398 self.FISValue = cp.deepcopy(self.Defuzzify(self.OutImpl))399 return self.FISValue400 def GetMaxAntecentKey(self):401 return max(self.InputFuzzyVals.iterkeys(), key=lambda k: self.InputFuzzyVals[k])402 def GetMaxAntecentOfMaxImplicationKey(self):403 AntecentList = self.InpPerRuleVals[self.GetMaxImplicationKey()]404 InpMax = AntecentList.index(max(AntecentList))405 return [self.Rules[self.GetMaxImplicationKey()][InpMax*2+1], self.Rules[self.GetMaxImplicationKey()][InpMax*2+2]]406 def GetMaxImplicationKey(self):407 return list(self.Rules)[self.OutImpl.index(max(self.OutImpl))]408 def GetInputVariables(self):409 return self.Input.keys()410 def PlotRules(self, NumSupportPoints=50):411 '''412 Plots all rules of the FIS413 '''414 for iRule in self.Rules.keys():415 RuleDef = self.Rules[iRule]416 nRules = (len(RuleDef)-4)/2417 MFdict = dict()418 for iInput in range(nRules):419 iInputKey = RuleDef[1+iInput*2]420 iMFKey = RuleDef[2+iInput*2]421 MFdict['In "'+iInputKey+'-'+iMFKey+'"'] = list()422 iRange = self.Input[iInputKey]['Range']423 xVals = iRange[0] + (iRange[1]-iRange[0])*np.linspace(0.,1.,num=NumSupportPoints)424 for iX in xVals:425 MFdict['In "'+iInputKey+'-'+iMFKey+'"'].append(self.Input[iInputKey]['MF'][iMFKey](iX))426 iOutoutKey = RuleDef[-2]427 iMFKey = RuleDef[-1]428 MFdict['Out "'+iOutoutKey+'-'+iMFKey+'"'] = list()429 iRange = self.Output[iOutoutKey]['Range']430 xVals = iRange[0] + (iRange[1]-iRange[0])*np.linspace(0.,1.,num=NumSupportPoints)431 for iX in xVals:432 MFdict['Out "'+iOutoutKey+'-'+iMFKey+'"'].append(self.Output[iOutoutKey]['MF'][iMFKey](iX))433 Iter = np.linspace(0.,1.,num=NumSupportPoints)434 self._InputOutputPlot(Iter,MFdict,Label='Rule "'+iRule+'" with "'+RuleDef[0]+'"')435 def PlotInputOutputMFs(self, NumSupportPoints=50):436 '''437 Plots input and output membership functions of the FIS438 '''439 for iInput in self.Input.keys():440 iRange = self.Input[iInput]['Range']441 xVals = iRange[0] + (iRange[1]-iRange[0])*np.linspace(0.,1.,num=NumSupportPoints)442 MFdict = dict()443 for iMF in self.Input[iInput]['MF'].keys():444 MFdict['MF "'+iMF+'"'] = list()445 for iX in xVals:446 MFdict['MF "'+iMF+'"'].append(self.Input[iInput]['MF'][iMF](iX))447 self._InputOutputPlot(xVals,MFdict,Label='Fuzzy input membership functions of '+iInput)448 for iOutput in self.Output.keys():449 iRange = self.Output[iOutput]['Range']450 xVals = iRange[0] + (iRange[1]-iRange[0])*np.linspace(0.,1.,num=NumSupportPoints)451 MFdict = dict()452 for iMF in self.Output[iOutput]['MF'].keys():453 MFdict['MF "'+iMF+'"'] = list()454 for iX in xVals:455 MFdict['MF "'+iMF+'"'].append(self.Output[iOutput]['MF'][iMF](iX))456 self._InputOutputPlot(xVals,MFdict,Label='Fuzzy output membership functions of '+iOutput)457 def PlotFuzzyInferenceSystem(self, UseTex=False, NumSupportPoints=20, \458 ShowFig=True, FigFile=None, nRulesPerPlot=7.):459 '''460 Plot the whole fuzzy inference system over rules461 '''462 try:463 from mpl_toolkits.mplot3d import Axes3D464 import matplotlib.pyplot as plt465 from matplotlib import cm466 except:467 logging.error('Matplotlib could not be imported!')468 # Initializations469 plt.rc('text', usetex=UseTex)470 Rules = self.Rules.keys()471 nRules = len(Rules)472 iPlot = 1473 nPlots = math.floor(nRules/nRulesPerPlot)+math.ceil(nRules%nRulesPerPlot/10.)474 Inputs = self.Input.keys()475 nInputs = len(Inputs)476 FigureTitle = 'FIS of '+self.FISname477 if hasattr(self, 'FISValue'):478 PlotMEinfo = True479 FigureTitle += ' - %.3f'%(self.FISValue)480 else:481 PlotMEinfo = False482 # FIS plotting483 for RuleID, iRule in enumerate(Rules):484 if RuleID == 0:485 if nRules>nRulesPerPlot:486 fig = plt.figure(figsize=plt.figaspect(nRulesPerPlot/(nInputs+1.)))487 fig.suptitle( FigureTitle+'(Part %i/%i)'%(iPlot,nPlots), fontsize=14, fontweight='bold')488 nSubPlotY = nRulesPerPlot489 iPlot += 1490 else:491 fig = plt.figure(figsize=plt.figaspect(nRules/(nInputs+1.)))492 fig.suptitle( FigureTitle, fontsize=14, fontweight='bold')493 nSubPlotY = nRules494 iPlot += 1495 elif (RuleID)%(nRulesPerPlot) == 0:496 if math.floor((nRules - RuleID)/nRulesPerPlot) > 0:497 nRest = nRulesPerPlot498 else:499 nRest = int((nRules - RuleID)%nRulesPerPlot)500 fig = plt.figure(figsize=plt.figaspect(nRest/(nInputs+1.)))501 fig.suptitle( FigureTitle+'(Part %i/%i)'%(iPlot,nPlots), fontsize=14, fontweight='bold')502 nSubPlotY = nRest503 iPlot += 1504 for InputID, jInput in enumerate(Inputs):505 iInput = self.Rules[iRule][InputID*2+1]506 InputMFID = self.Rules[iRule][InputID*2+2]507 ax = fig.add_subplot( nSubPlotY, (nInputs+1.), \508 RuleID*(nInputs+1.)+InputID+1 - (iPlot-2)*nRulesPerPlot*(nInputs+1))509 X = np.linspace(self.Input[iInput]['Range'][0], \510 self.Input[iInput]['Range'][1],num=NumSupportPoints)511 Y = list()512 for iX in X:513 Y.append(self.Input[iInput]['MF'][InputMFID](iX))514 if InputID==0:515 yLabel = 'Rule %i:'%(RuleID)516 else:517 yLabel = []518 self._SubPlot(fig, ax, X, Y, iInput+' is "'+InputMFID+'"', [], yLabel)519 if PlotMEinfo:520 YTilde = [self.InpPerRuleVals[iRule][InputID]]*np.size(X)521 ax.plot(X, YTilde, 'r--')522 if RuleID<nRules-1:523 plt.setp( ax.get_xticklabels(), visible=False)524 if InputID>0:525 plt.setp( ax.get_yticklabels(), visible=False)526 # plot output527 Output = self.Rules[iRule][-2]528 OutputMFID = self.Rules[iRule][-1]529 ax = fig.add_subplot(nSubPlotY, (nInputs+1.), \530 RuleID*(nInputs+1.)+nInputs+1 - (iPlot-2)*nRulesPerPlot*(nInputs+1))531 X = np.linspace(self.Output[Output]['Range'][0], \532 self.Output[Output]['Range'][1],num=NumSupportPoints)533 Y = list()534 for iX in X:535 Y.append(self.Output[Output]['MF'][OutputMFID](iX))536 SubTitel = 'Output'537 self._SubPlot(fig, ax, X, Y, Output+': "'+OutputMFID+'"', [], [], ColorCode='r')538 if PlotMEinfo:539 YTilde = [self.OutImpl[RuleID]]*np.size(X)540 ax.plot(X, YTilde, 'r--')541 if RuleID<nRules-1:542 plt.setp( ax.get_xticklabels(), visible=False)543 plt.setp( ax.get_yticklabels(), visible=False)544 if FigFile != None:545 plt.savefig(FigFile)546 if ShowFig:547 plt.show()548 else:549 plt.close()550 def _SubPlot(self,fig, ax, xVals, yVals, SubTitel, xLabel, yLabel, ColorCode='b'):551 ax.plot(xVals, yVals, ColorCode)552 ax.set_autoscaley_on(False)553 ax.set_ylim([-.1, 1.1])554 if SubTitel:555 ax.set_title(SubTitel)556 if xLabel:557 ax.set_xlabel(xLabel, fontsize=12)558 if yLabel:559 ax.set_ylabel(yLabel, fontsize=12)560 def _InputOutputPlot(self,xVals,MFdict,Label='Fuzzy variable'):561 try:562 import matplotlib.pyplot as plt563 except:564 logging.fatal('Could not import matplotlib modules!')565 sys.exit('Failed to import matlotlib package!')566567 num_plots = len(MFdict.keys())568 plt.figure()569 plt.title(Label)570 colormap = plt.cm.gist_rainbow571 plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, num_plots)])572573 # Plot several different functions...574 labels = []575 for iMF in MFdict.keys():576 plt.plot(xVals,MFdict[iMF])577 labels.append(iMF)578 ax = plt.gca()579 box = ax.get_position()580 ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])581 ax.legend(labels, loc='center left', bbox_to_anchor=(1, 0.5)) ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful