code
stringlengths 13
6.09M
| order_type
stringclasses 2
values | original_example
dict | step_ids
listlengths 1
5
|
---|---|---|---|
<|reserved_special_token_0|>
class Notification(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class SendMail(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.address = config.sendmail.address
self.contact_info = config.sendmail.contact_info
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def notify(self, recipient, message):
cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.
contact_info[recipient]['address']]
msg = self.message_template.format(self.contact_info[recipient][
'address'], self.contact_info[recipient]['name'], message)
proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=msg.encode('utf-8'))
def connect(self):
pass
def close(self):
pass
class SMTP(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.hostname = config.smtp.hostname
self.username = config.smtp.username
self.passwd = config.smtp.passwd
self.address = config.smtp.address
self.contact_info = config.smtp.contact_info
self.connected = False
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def connect(self):
self.server = smtplib.SMTP(self.hostname)
self.server.ehlo()
self.server.starttls()
self.server.login(self.username, self.passwd)
self.connected = True
def notify(self, recipient, message):
if not self.connected:
raise NotifyError(
'Not connected to SMTP server; cannot send notifications')
self.server.sendmail(self.address, self.contact_info[recipient][
'address'], self.message_template.format(self.contact_info[
recipient]['address'], self.contact_info[recipient]['name'],
message))
def close(self):
if self.connected:
self.server.quit()
self.connected = False
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Notification(object):
def __init__(self, config, dry_run):
self.dry_run = dry_run
self.notifications = {}
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class SendMail(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.address = config.sendmail.address
self.contact_info = config.sendmail.contact_info
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def notify(self, recipient, message):
cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.
contact_info[recipient]['address']]
msg = self.message_template.format(self.contact_info[recipient][
'address'], self.contact_info[recipient]['name'], message)
proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=msg.encode('utf-8'))
def connect(self):
pass
def close(self):
pass
class SMTP(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.hostname = config.smtp.hostname
self.username = config.smtp.username
self.passwd = config.smtp.passwd
self.address = config.smtp.address
self.contact_info = config.smtp.contact_info
self.connected = False
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def connect(self):
self.server = smtplib.SMTP(self.hostname)
self.server.ehlo()
self.server.starttls()
self.server.login(self.username, self.passwd)
self.connected = True
def notify(self, recipient, message):
if not self.connected:
raise NotifyError(
'Not connected to SMTP server; cannot send notifications')
self.server.sendmail(self.address, self.contact_info[recipient][
'address'], self.message_template.format(self.contact_info[
recipient]['address'], self.contact_info[recipient]['name'],
message))
def close(self):
if self.connected:
self.server.quit()
self.connected = False
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Notification(object):
def __init__(self, config, dry_run):
self.dry_run = dry_run
self.notifications = {}
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def notify(self, recipient, message):
raise NotImplementedError('Need to subclass Notification')
def connect(self):
raise NotImplementedError('Need to subclass Notification')
def close(self):
raise NotImplementedError('Need to subclass Notification')
class SendMail(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.address = config.sendmail.address
self.contact_info = config.sendmail.contact_info
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def notify(self, recipient, message):
cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.
contact_info[recipient]['address']]
msg = self.message_template.format(self.contact_info[recipient][
'address'], self.contact_info[recipient]['name'], message)
proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=msg.encode('utf-8'))
def connect(self):
pass
def close(self):
pass
class SMTP(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.hostname = config.smtp.hostname
self.username = config.smtp.username
self.passwd = config.smtp.passwd
self.address = config.smtp.address
self.contact_info = config.smtp.contact_info
self.connected = False
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def connect(self):
self.server = smtplib.SMTP(self.hostname)
self.server.ehlo()
self.server.starttls()
self.server.login(self.username, self.passwd)
self.connected = True
def notify(self, recipient, message):
if not self.connected:
raise NotifyError(
'Not connected to SMTP server; cannot send notifications')
self.server.sendmail(self.address, self.contact_info[recipient][
'address'], self.message_template.format(self.contact_info[
recipient]['address'], self.contact_info[recipient]['name'],
message))
def close(self):
if self.connected:
self.server.quit()
self.connected = False
<|reserved_special_token_1|>
import smtplib
import subprocess
import time
class NotifyError(Exception):
def __init__(self, message):
self.message = message
class Notification(object):
def __init__(self, config, dry_run):
self.dry_run = dry_run
self.notifications = {}
def submit(self, recipient, message):
if recipient not in self.notifications:
self.notifications[recipient] = []
self.notifications[recipient].append(message)
def notify_all(self):
for recip in self.notifications:
if len(self.notifications[recip]) > 0:
self.notify(recip, '\r\n\r\n-------------------\r\n\r\n'.
join(self.notifications[recip]))
time.sleep(5)
self.notifications[recip] = []
def notify(self, recipient, message):
raise NotImplementedError('Need to subclass Notification')
def connect(self):
raise NotImplementedError('Need to subclass Notification')
def close(self):
raise NotImplementedError('Need to subclass Notification')
class SendMail(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.address = config.sendmail.address
self.contact_info = config.sendmail.contact_info
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def notify(self, recipient, message):
cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.
contact_info[recipient]['address']]
msg = self.message_template.format(self.contact_info[recipient][
'address'], self.contact_info[recipient]['name'], message)
proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate(input=msg.encode('utf-8'))
def connect(self):
pass
def close(self):
pass
class SMTP(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.hostname = config.smtp.hostname
self.username = config.smtp.username
self.passwd = config.smtp.passwd
self.address = config.smtp.address
self.contact_info = config.smtp.contact_info
self.connected = False
self.message_template = '\r\n'.join(['From: ' + self.address,
'To: {}', 'Subject: [' + config.name + '] Notifications', '',
'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +
' Bot'])
def connect(self):
self.server = smtplib.SMTP(self.hostname)
self.server.ehlo()
self.server.starttls()
self.server.login(self.username, self.passwd)
self.connected = True
def notify(self, recipient, message):
if not self.connected:
raise NotifyError(
'Not connected to SMTP server; cannot send notifications')
self.server.sendmail(self.address, self.contact_info[recipient][
'address'], self.message_template.format(self.contact_info[
recipient]['address'], self.contact_info[recipient]['name'],
message))
def close(self):
if self.connected:
self.server.quit()
self.connected = False
<|reserved_special_token_1|>
import smtplib
import subprocess
import time
class NotifyError(Exception):
def __init__(self, message):
self.message = message
class Notification(object):
def __init__(self, config, dry_run):
self.dry_run = dry_run
self.notifications = {}
def submit(self, recipient, message):
if recipient not in self.notifications:
self.notifications[recipient] = []
self.notifications[recipient].append(message)
def notify_all(self):
for recip in self.notifications:
if len(self.notifications[recip]) > 0:
self.notify(recip, '\r\n\r\n-------------------\r\n\r\n'.join(self.notifications[recip]))
time.sleep(5)
self.notifications[recip] = []
def notify(self, recipient, message):
raise NotImplementedError('Need to subclass Notification')
def connect(self):
raise NotImplementedError('Need to subclass Notification')
def close(self):
raise NotImplementedError('Need to subclass Notification')
class SendMail(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.address = config.sendmail.address
self.contact_info = config.sendmail.contact_info
self.message_template = '\r\n'.join(['From: '+self.address,
'To: {}',
'Subject: ['+config.name+'] Notifications',
'',
'Greetings Human {},',
'',
'{}'
'',
'',
'Beep boop,',
config.name + ' Bot'])
def notify(self, recipient, message):
# -i flag: do NOT treat bare dot as EOF
cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.contact_info[recipient]['address']]
msg = self.message_template.format(self.contact_info[recipient]['address'], self.contact_info[recipient]['name'], message)
proc = subprocess.Popen(cmd, shell=False,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = proc.communicate(input=msg.encode('utf-8'))
#TODO handle errors
#print(f"ret: {proc.returncode}")
#print("stdout:" + str(out))
#print("stderr:" + str(err))
def connect(self):
pass
def close(self):
pass
class SMTP(Notification):
def __init__(self, config, dry_run):
super().__init__(config, dry_run)
self.hostname = config.smtp.hostname
self.username = config.smtp.username
self.passwd = config.smtp.passwd
self.address = config.smtp.address
self.contact_info = config.smtp.contact_info
self.connected = False
self.message_template = '\r\n'.join(['From: '+self.address,
'To: {}',
'Subject: ['+config.name+'] Notifications',
'',
'Greetings Human {},',
'',
'{}'
'',
'',
'Beep boop,',
config.name + ' Bot'])
#TODO deal with smtplib exceptions
def connect(self):
self.server = smtplib.SMTP(self.hostname)
self.server.ehlo()
self.server.starttls()
self.server.login(self.username, self.passwd)
self.connected = True
#TODO implement saving messages to disk with timestamp if send fails
#TODO deal with smtplib exceptions
def notify(self, recipient, message):
if not self.connected:
raise NotifyError('Not connected to SMTP server; cannot send notifications')
self.server.sendmail(self.address,
self.contact_info[recipient]['address'],
self.message_template.format(self.contact_info[recipient]['address'], self.contact_info[recipient]['name'], message)
)
#TODO deal with smtplib exceptions
def close(self):
if self.connected:
self.server.quit()
self.connected = False
|
flexible
|
{
"blob_id": "01849a6bf5ce5eb75c549af28312f61711ad2494",
"index": 4425,
"step-1": "<mask token>\n\n\nclass Notification(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SendMail(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.address = config.sendmail.address\n self.contact_info = config.sendmail.contact_info\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def notify(self, recipient, message):\n cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.\n contact_info[recipient]['address']]\n msg = self.message_template.format(self.contact_info[recipient][\n 'address'], self.contact_info[recipient]['name'], message)\n proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = proc.communicate(input=msg.encode('utf-8'))\n\n def connect(self):\n pass\n\n def close(self):\n pass\n\n\nclass SMTP(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.hostname = config.smtp.hostname\n self.username = config.smtp.username\n self.passwd = config.smtp.passwd\n self.address = config.smtp.address\n self.contact_info = config.smtp.contact_info\n self.connected = False\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def connect(self):\n self.server = smtplib.SMTP(self.hostname)\n self.server.ehlo()\n self.server.starttls()\n self.server.login(self.username, self.passwd)\n self.connected = True\n\n def notify(self, recipient, message):\n if not self.connected:\n raise NotifyError(\n 'Not connected to SMTP server; cannot send notifications')\n self.server.sendmail(self.address, self.contact_info[recipient][\n 'address'], self.message_template.format(self.contact_info[\n recipient]['address'], self.contact_info[recipient]['name'],\n message))\n\n def close(self):\n if self.connected:\n self.server.quit()\n self.connected = False\n",
"step-2": "<mask token>\n\n\nclass Notification(object):\n\n def __init__(self, config, dry_run):\n self.dry_run = dry_run\n self.notifications = {}\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SendMail(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.address = config.sendmail.address\n self.contact_info = config.sendmail.contact_info\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def notify(self, recipient, message):\n cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.\n contact_info[recipient]['address']]\n msg = self.message_template.format(self.contact_info[recipient][\n 'address'], self.contact_info[recipient]['name'], message)\n proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = proc.communicate(input=msg.encode('utf-8'))\n\n def connect(self):\n pass\n\n def close(self):\n pass\n\n\nclass SMTP(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.hostname = config.smtp.hostname\n self.username = config.smtp.username\n self.passwd = config.smtp.passwd\n self.address = config.smtp.address\n self.contact_info = config.smtp.contact_info\n self.connected = False\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def connect(self):\n self.server = smtplib.SMTP(self.hostname)\n self.server.ehlo()\n self.server.starttls()\n self.server.login(self.username, self.passwd)\n self.connected = True\n\n def notify(self, recipient, message):\n if not self.connected:\n raise NotifyError(\n 'Not connected to SMTP server; cannot send notifications')\n self.server.sendmail(self.address, self.contact_info[recipient][\n 'address'], self.message_template.format(self.contact_info[\n recipient]['address'], self.contact_info[recipient]['name'],\n message))\n\n def close(self):\n if self.connected:\n self.server.quit()\n self.connected = False\n",
"step-3": "<mask token>\n\n\nclass Notification(object):\n\n def __init__(self, config, dry_run):\n self.dry_run = dry_run\n self.notifications = {}\n <mask token>\n <mask token>\n\n def notify(self, recipient, message):\n raise NotImplementedError('Need to subclass Notification')\n\n def connect(self):\n raise NotImplementedError('Need to subclass Notification')\n\n def close(self):\n raise NotImplementedError('Need to subclass Notification')\n\n\nclass SendMail(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.address = config.sendmail.address\n self.contact_info = config.sendmail.contact_info\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def notify(self, recipient, message):\n cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.\n contact_info[recipient]['address']]\n msg = self.message_template.format(self.contact_info[recipient][\n 'address'], self.contact_info[recipient]['name'], message)\n proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = proc.communicate(input=msg.encode('utf-8'))\n\n def connect(self):\n pass\n\n def close(self):\n pass\n\n\nclass SMTP(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.hostname = config.smtp.hostname\n self.username = config.smtp.username\n self.passwd = config.smtp.passwd\n self.address = config.smtp.address\n self.contact_info = config.smtp.contact_info\n self.connected = False\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def connect(self):\n self.server = smtplib.SMTP(self.hostname)\n self.server.ehlo()\n self.server.starttls()\n self.server.login(self.username, self.passwd)\n self.connected = True\n\n def notify(self, recipient, message):\n if not self.connected:\n raise NotifyError(\n 'Not connected to SMTP server; cannot send notifications')\n self.server.sendmail(self.address, self.contact_info[recipient][\n 'address'], self.message_template.format(self.contact_info[\n recipient]['address'], self.contact_info[recipient]['name'],\n message))\n\n def close(self):\n if self.connected:\n self.server.quit()\n self.connected = False\n",
"step-4": "import smtplib\nimport subprocess\nimport time\n\n\nclass NotifyError(Exception):\n\n def __init__(self, message):\n self.message = message\n\n\nclass Notification(object):\n\n def __init__(self, config, dry_run):\n self.dry_run = dry_run\n self.notifications = {}\n\n def submit(self, recipient, message):\n if recipient not in self.notifications:\n self.notifications[recipient] = []\n self.notifications[recipient].append(message)\n\n def notify_all(self):\n for recip in self.notifications:\n if len(self.notifications[recip]) > 0:\n self.notify(recip, '\\r\\n\\r\\n-------------------\\r\\n\\r\\n'.\n join(self.notifications[recip]))\n time.sleep(5)\n self.notifications[recip] = []\n\n def notify(self, recipient, message):\n raise NotImplementedError('Need to subclass Notification')\n\n def connect(self):\n raise NotImplementedError('Need to subclass Notification')\n\n def close(self):\n raise NotImplementedError('Need to subclass Notification')\n\n\nclass SendMail(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.address = config.sendmail.address\n self.contact_info = config.sendmail.contact_info\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def notify(self, recipient, message):\n cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.\n contact_info[recipient]['address']]\n msg = self.message_template.format(self.contact_info[recipient][\n 'address'], self.contact_info[recipient]['name'], message)\n proc = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n out, err = proc.communicate(input=msg.encode('utf-8'))\n\n def connect(self):\n pass\n\n def close(self):\n pass\n\n\nclass SMTP(Notification):\n\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.hostname = config.smtp.hostname\n self.username = config.smtp.username\n self.passwd = config.smtp.passwd\n self.address = config.smtp.address\n self.contact_info = config.smtp.contact_info\n self.connected = False\n self.message_template = '\\r\\n'.join(['From: ' + self.address,\n 'To: {}', 'Subject: [' + config.name + '] Notifications', '',\n 'Greetings Human {},', '', '{}', '', 'Beep boop,', config.name +\n ' Bot'])\n\n def connect(self):\n self.server = smtplib.SMTP(self.hostname)\n self.server.ehlo()\n self.server.starttls()\n self.server.login(self.username, self.passwd)\n self.connected = True\n\n def notify(self, recipient, message):\n if not self.connected:\n raise NotifyError(\n 'Not connected to SMTP server; cannot send notifications')\n self.server.sendmail(self.address, self.contact_info[recipient][\n 'address'], self.message_template.format(self.contact_info[\n recipient]['address'], self.contact_info[recipient]['name'],\n message))\n\n def close(self):\n if self.connected:\n self.server.quit()\n self.connected = False\n",
"step-5": "import smtplib\nimport subprocess\nimport time\n\nclass NotifyError(Exception):\n def __init__(self, message):\n self.message = message\n\nclass Notification(object):\n def __init__(self, config, dry_run):\n self.dry_run = dry_run\n self.notifications = {}\n\n def submit(self, recipient, message):\n if recipient not in self.notifications:\n self.notifications[recipient] = []\n self.notifications[recipient].append(message)\n\n def notify_all(self):\n for recip in self.notifications:\n if len(self.notifications[recip]) > 0:\n self.notify(recip, '\\r\\n\\r\\n-------------------\\r\\n\\r\\n'.join(self.notifications[recip]))\n time.sleep(5)\n self.notifications[recip] = []\n\n def notify(self, recipient, message):\n raise NotImplementedError('Need to subclass Notification')\n\n def connect(self):\n raise NotImplementedError('Need to subclass Notification')\n \n def close(self):\n raise NotImplementedError('Need to subclass Notification')\n\n\nclass SendMail(Notification):\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.address = config.sendmail.address\n self.contact_info = config.sendmail.contact_info\n self.message_template = '\\r\\n'.join(['From: '+self.address,\n 'To: {}',\n 'Subject: ['+config.name+'] Notifications',\n '',\n 'Greetings Human {},',\n '',\n '{}'\n '',\n '',\n 'Beep boop,',\n config.name + ' Bot'])\n\n def notify(self, recipient, message):\n # -i flag: do NOT treat bare dot as EOF\n cmd = ['/usr/sbin/sendmail', f'-f {self.address}', self.contact_info[recipient]['address']]\n msg = self.message_template.format(self.contact_info[recipient]['address'], self.contact_info[recipient]['name'], message)\n proc = subprocess.Popen(cmd, shell=False,\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = proc.communicate(input=msg.encode('utf-8'))\n #TODO handle errors\n #print(f\"ret: {proc.returncode}\")\n #print(\"stdout:\" + str(out))\n #print(\"stderr:\" + str(err))\n\n def connect(self):\n pass\n\n def close(self):\n pass\n\nclass SMTP(Notification):\n def __init__(self, config, dry_run):\n super().__init__(config, dry_run)\n self.hostname = config.smtp.hostname\n self.username = config.smtp.username\n self.passwd = config.smtp.passwd\n self.address = config.smtp.address\n self.contact_info = config.smtp.contact_info\n self.connected = False\n self.message_template = '\\r\\n'.join(['From: '+self.address,\n 'To: {}',\n 'Subject: ['+config.name+'] Notifications',\n '',\n 'Greetings Human {},',\n '',\n '{}'\n '',\n '',\n 'Beep boop,',\n config.name + ' Bot'])\n\n #TODO deal with smtplib exceptions\n def connect(self):\n self.server = smtplib.SMTP(self.hostname)\n self.server.ehlo()\n self.server.starttls()\n self.server.login(self.username, self.passwd)\n self.connected = True\n\n #TODO implement saving messages to disk with timestamp if send fails\n #TODO deal with smtplib exceptions\n def notify(self, recipient, message):\n if not self.connected:\n raise NotifyError('Not connected to SMTP server; cannot send notifications')\n self.server.sendmail(self.address, \n\t\t\t\tself.contact_info[recipient]['address'], \n\t\t\t\tself.message_template.format(self.contact_info[recipient]['address'], self.contact_info[recipient]['name'], message)\n )\n\n #TODO deal with smtplib exceptions\n def close(self):\n if self.connected: \n self.server.quit()\n self.connected = False\n\n\n\n",
"step-ids": [
11,
12,
15,
20,
21
]
}
|
[
11,
12,
15,
20,
21
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if __name__ == '__main__':
game = tools.Game(setup.STATE_DICT, 'menu')
game.run()
<|reserved_special_token_1|>
from source import tools, setup
if __name__ == '__main__':
game = tools.Game(setup.STATE_DICT, 'menu')
game.run()
|
flexible
|
{
"blob_id": "a7deec1693c411988445528dceb602bf69e47d21",
"index": 2532,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n game = tools.Game(setup.STATE_DICT, 'menu')\n game.run()\n",
"step-3": "from source import tools, setup\nif __name__ == '__main__':\n game = tools.Game(setup.STATE_DICT, 'menu')\n game.run()\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def calc_fib(n):
fib_lis = dict()
for i in range(n + 1):
if i <= 1:
fib_lis[i] = i
else:
fib_lis[i] = fib_lis[i - 2] + fib_lis[i - 1]
return fib_lis[n]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def calc_fib(n):
fib_lis = dict()
for i in range(n + 1):
if i <= 1:
fib_lis[i] = i
else:
fib_lis[i] = fib_lis[i - 2] + fib_lis[i - 1]
return fib_lis[n]
<|reserved_special_token_0|>
print(calc_fib(n))
<|reserved_special_token_1|>
def calc_fib(n):
fib_lis = dict()
for i in range(n + 1):
if i <= 1:
fib_lis[i] = i
else:
fib_lis[i] = fib_lis[i - 2] + fib_lis[i - 1]
return fib_lis[n]
n = int(input())
print(calc_fib(n))
<|reserved_special_token_1|>
def calc_fib(n):
fib_lis = dict()
for i in range(n+1):
if (i <= 1):
fib_lis[i] = i
else:
fib_lis[i] = fib_lis[i-2] + fib_lis[i-1]
return fib_lis[n]
n = int(input())
print(calc_fib(n))
|
flexible
|
{
"blob_id": "426b711571d3b5c4f8c7b0bad3a613951902e60b",
"index": 4129,
"step-1": "<mask token>\n",
"step-2": "def calc_fib(n):\n fib_lis = dict()\n for i in range(n + 1):\n if i <= 1:\n fib_lis[i] = i\n else:\n fib_lis[i] = fib_lis[i - 2] + fib_lis[i - 1]\n return fib_lis[n]\n\n\n<mask token>\n",
"step-3": "def calc_fib(n):\n fib_lis = dict()\n for i in range(n + 1):\n if i <= 1:\n fib_lis[i] = i\n else:\n fib_lis[i] = fib_lis[i - 2] + fib_lis[i - 1]\n return fib_lis[n]\n\n\n<mask token>\nprint(calc_fib(n))\n",
"step-4": "def calc_fib(n):\n fib_lis = dict()\n for i in range(n + 1):\n if i <= 1:\n fib_lis[i] = i\n else:\n fib_lis[i] = fib_lis[i - 2] + fib_lis[i - 1]\n return fib_lis[n]\n\n\nn = int(input())\nprint(calc_fib(n))\n",
"step-5": "def calc_fib(n):\n fib_lis = dict()\n for i in range(n+1):\n if (i <= 1):\n fib_lis[i] = i\n else:\n fib_lis[i] = fib_lis[i-2] + fib_lis[i-1]\n return fib_lis[n]\nn = int(input())\nprint(calc_fib(n))\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
dependencies = [('api', '0006_order_date')]
operations = [migrations.RemoveField(model_name='order', name='product'
), migrations.AddField(model_name='order', name='product', field=
models.ManyToManyField(to='api.Product')), migrations.AlterField(
model_name='order', name='status', field=models.TextField(default=
'неплачено', max_length=50))]
<|reserved_special_token_1|>
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('api', '0006_order_date')]
operations = [migrations.RemoveField(model_name='order', name='product'
), migrations.AddField(model_name='order', name='product', field=
models.ManyToManyField(to='api.Product')), migrations.AlterField(
model_name='order', name='status', field=models.TextField(default=
'неплачено', max_length=50))]
<|reserved_special_token_1|>
# Generated by Django 3.0.5 on 2020-04-25 12:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0006_order_date'),
]
operations = [
migrations.RemoveField(
model_name='order',
name='product',
),
migrations.AddField(
model_name='order',
name='product',
field=models.ManyToManyField(to='api.Product'),
),
migrations.AlterField(
model_name='order',
name='status',
field=models.TextField(default='неплачено', max_length=50),
),
]
|
flexible
|
{
"blob_id": "4cc138016cb1f82e12c76c185be19188d3e38bf9",
"index": 2186,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('api', '0006_order_date')]\n operations = [migrations.RemoveField(model_name='order', name='product'\n ), migrations.AddField(model_name='order', name='product', field=\n models.ManyToManyField(to='api.Product')), migrations.AlterField(\n model_name='order', name='status', field=models.TextField(default=\n 'неплачено', max_length=50))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('api', '0006_order_date')]\n operations = [migrations.RemoveField(model_name='order', name='product'\n ), migrations.AddField(model_name='order', name='product', field=\n models.ManyToManyField(to='api.Product')), migrations.AlterField(\n model_name='order', name='status', field=models.TextField(default=\n 'неплачено', max_length=50))]\n",
"step-5": "# Generated by Django 3.0.5 on 2020-04-25 12:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0006_order_date'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='order',\n name='product',\n ),\n migrations.AddField(\n model_name='order',\n name='product',\n field=models.ManyToManyField(to='api.Product'),\n ),\n migrations.AlterField(\n model_name='order',\n name='status',\n field=models.TextField(default='неплачено', max_length=50),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from .alexnet import *
from .lenet import *
from .net import *
from .vae import *
|
flexible
|
{
"blob_id": "56d5915d30e85285da549cc69ef25714bacc6f3a",
"index": 8304,
"step-1": "<mask token>\n",
"step-2": "from .alexnet import *\nfrom .lenet import *\nfrom .net import *\nfrom .vae import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
import csv
import tweepy
import pandas as pd
####input your credentials here
from tweepy.auth import OAuthHandler
auth = OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj', 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')
auth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7', 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')
auth = tweepy.OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj', 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')
auth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7', 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')
api = tweepy.API(auth,wait_on_rate_limit=True)
csvFile = open('data.csv', 'a')
csvWriter = csv.writer(csvFile)
for tweet in tweepy.Cursor(api.search,q="#ootd",count=100,
include_entities=True,
lang="en",
since="2018-11-01").items():
if 'media' in tweet.entities:
for image in tweet.entities['media']:
favs = tweet.favorite_count
if favs > 30:
csvWriter.writerow([favs, image['media_url'], tweet.created_at])
|
normal
|
{
"blob_id": "b68cc09347584dfc613b2e38d036b124c9af7952",
"index": 1904,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7',\n 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\n<mask token>\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7',\n 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\n<mask token>\nfor tweet in tweepy.Cursor(api.search, q='#ootd', count=100,\n include_entities=True, lang='en', since='2018-11-01').items():\n if 'media' in tweet.entities:\n for image in tweet.entities['media']:\n favs = tweet.favorite_count\n if favs > 30:\n csvWriter.writerow([favs, image['media_url'], tweet.created_at]\n )\n",
"step-3": "<mask token>\nauth = OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj',\n 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7',\n 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\nauth = tweepy.OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj',\n 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7',\n 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\napi = tweepy.API(auth, wait_on_rate_limit=True)\ncsvFile = open('data.csv', 'a')\ncsvWriter = csv.writer(csvFile)\nfor tweet in tweepy.Cursor(api.search, q='#ootd', count=100,\n include_entities=True, lang='en', since='2018-11-01').items():\n if 'media' in tweet.entities:\n for image in tweet.entities['media']:\n favs = tweet.favorite_count\n if favs > 30:\n csvWriter.writerow([favs, image['media_url'], tweet.created_at]\n )\n",
"step-4": "import csv\nimport tweepy\nimport pandas as pd\nfrom tweepy.auth import OAuthHandler\nauth = OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj',\n 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7',\n 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\nauth = tweepy.OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj',\n 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7',\n 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\napi = tweepy.API(auth, wait_on_rate_limit=True)\ncsvFile = open('data.csv', 'a')\ncsvWriter = csv.writer(csvFile)\nfor tweet in tweepy.Cursor(api.search, q='#ootd', count=100,\n include_entities=True, lang='en', since='2018-11-01').items():\n if 'media' in tweet.entities:\n for image in tweet.entities['media']:\n favs = tweet.favorite_count\n if favs > 30:\n csvWriter.writerow([favs, image['media_url'], tweet.created_at]\n )\n",
"step-5": "import csv\nimport tweepy\nimport pandas as pd\n####input your credentials here\nfrom tweepy.auth import OAuthHandler\nauth = OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj', 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7', 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\n\nauth = tweepy.OAuthHandler('WNUpykrIjiGF0NKoV7qk7uiNj', 'Nhe0GjOkbaQKbPMLTqcAYQnqMnz3Edpdup28h2R2KqRLa6iBDN')\nauth.set_access_token('956917059287375875-EThit80MxgQPTJlh7ZObqyHsoV8Q2D7', 'eLv893meGppqfX3xOr8SJ93kpsbZpoOiRsVM3XTgJryZM')\napi = tweepy.API(auth,wait_on_rate_limit=True)\ncsvFile = open('data.csv', 'a')\ncsvWriter = csv.writer(csvFile)\n\nfor tweet in tweepy.Cursor(api.search,q=\"#ootd\",count=100,\n include_entities=True,\n lang=\"en\",\n since=\"2018-11-01\").items():\n\n if 'media' in tweet.entities:\n for image in tweet.entities['media']:\n favs = tweet.favorite_count\n if favs > 30:\n csvWriter.writerow([favs, image['media_url'], tweet.created_at])",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class CreatePasswordEmailValidationSerializer(serializers.Serializer):
<|reserved_special_token_0|>
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class CreateEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[user_with_email_not_existing])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class EmailSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class EmailValidationSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email', 'validation_code']
class EmailValidationPasswordSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=200)
class Meta:
model = EmailValidation
fields = ['email', 'validation_code', 'password']
class NewUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
data['user'] = FullUserSerializer(self.user).data
return data
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CreatePasswordEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[email_does_exist])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class CreateEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[user_with_email_not_existing])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class EmailSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class EmailValidationSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email', 'validation_code']
class EmailValidationPasswordSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=200)
class Meta:
model = EmailValidation
fields = ['email', 'validation_code', 'password']
class NewUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
data['user'] = FullUserSerializer(self.user).data
return data
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def user_with_email_not_existing(email):
try:
User.objects.get(email=email)
raise ValidationError(message='This email is taken')
except User.DoesNotExist:
return email
def email_does_exist(email):
try:
User.objects.get(email=email)
return email
except User.DoesNotExist:
raise ValidationError(message='User does not exist!')
class CreatePasswordEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[email_does_exist])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class CreateEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[user_with_email_not_existing])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class EmailSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class EmailValidationSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email', 'validation_code']
class EmailValidationPasswordSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=200)
class Meta:
model = EmailValidation
fields = ['email', 'validation_code', 'password']
class NewUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
data['user'] = FullUserSerializer(self.user).data
return data
<|reserved_special_token_1|>
<|reserved_special_token_0|>
User = get_user_model()
def user_with_email_not_existing(email):
try:
User.objects.get(email=email)
raise ValidationError(message='This email is taken')
except User.DoesNotExist:
return email
def email_does_exist(email):
try:
User.objects.get(email=email)
return email
except User.DoesNotExist:
raise ValidationError(message='User does not exist!')
class CreatePasswordEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[email_does_exist])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class CreateEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[user_with_email_not_existing])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(validation_code=validation_code, to=
self.validated_data.get('email'), type=self.validated_data.get(
'type'))
new_validation = EmailValidation.objects.create(validation_code=
validation_code, email=email, type=self.validated_data.get('type'))
return new_validation
class EmailSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class EmailValidationSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email', 'validation_code']
class EmailValidationPasswordSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=200)
class Meta:
model = EmailValidation
fields = ['email', 'validation_code', 'password']
class NewUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
data['user'] = FullUserSerializer(self.user).data
return data
<|reserved_special_token_1|>
from random import randrange
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import EmailValidation
from ..emails.models import Email
from ..users.serializers import FullUserSerializer
User = get_user_model()
def user_with_email_not_existing(email):
try:
User.objects.get(email=email)
raise ValidationError(message='This email is taken')
except User.DoesNotExist:
return email
def email_does_exist(email):
try:
User.objects.get(email=email)
return email
except User.DoesNotExist:
raise ValidationError(message='User does not exist!')
class CreatePasswordEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[email_does_exist])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(
validation_code=validation_code,
to=self.validated_data.get('email'),
type=self.validated_data.get('type')
)
new_validation = EmailValidation.objects.create(
validation_code=validation_code,
email=email,
type=self.validated_data.get('type'))
return new_validation
class CreateEmailValidationSerializer(serializers.Serializer):
email = serializers.EmailField(validators=[user_with_email_not_existing])
def save(self):
validation_code = randrange(10000000, 100000000)
email = Email.objects.create(
validation_code=validation_code,
to=self.validated_data.get('email'),
type=self.validated_data.get('type')
)
new_validation = EmailValidation.objects.create(
validation_code=validation_code,
email=email,
type=self.validated_data.get('type'))
return new_validation
class EmailSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class EmailValidationSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email', 'validation_code']
class EmailValidationPasswordSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=200)
class Meta:
model = EmailValidation
fields = ['email', 'validation_code', 'password']
class NewUserSerializer(serializers.ModelSerializer):
email = serializers.EmailField()
class Meta:
model = EmailValidation
fields = ['email']
class TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):
def validate(self, attrs):
data = super().validate(attrs)
refresh = self.get_token(self.user)
data['refresh'] = str(refresh)
data['access'] = str(refresh.access_token)
data['user'] = FullUserSerializer(self.user).data
return data
|
flexible
|
{
"blob_id": "9f34bf3a0bb24db428b7af1a354aec1d3a72df98",
"index": 359,
"step-1": "<mask token>\n\n\nclass CreatePasswordEmailValidationSerializer(serializers.Serializer):\n <mask token>\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass CreateEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[user_with_email_not_existing])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass EmailSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass EmailValidationSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code']\n\n\nclass EmailValidationPasswordSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n password = serializers.CharField(max_length=200)\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code', 'password']\n\n\nclass NewUserSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):\n\n def validate(self, attrs):\n data = super().validate(attrs)\n refresh = self.get_token(self.user)\n data['refresh'] = str(refresh)\n data['access'] = str(refresh.access_token)\n data['user'] = FullUserSerializer(self.user).data\n return data\n",
"step-2": "<mask token>\n\n\nclass CreatePasswordEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[email_does_exist])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass CreateEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[user_with_email_not_existing])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass EmailSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass EmailValidationSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code']\n\n\nclass EmailValidationPasswordSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n password = serializers.CharField(max_length=200)\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code', 'password']\n\n\nclass NewUserSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):\n\n def validate(self, attrs):\n data = super().validate(attrs)\n refresh = self.get_token(self.user)\n data['refresh'] = str(refresh)\n data['access'] = str(refresh.access_token)\n data['user'] = FullUserSerializer(self.user).data\n return data\n",
"step-3": "<mask token>\n\n\ndef user_with_email_not_existing(email):\n try:\n User.objects.get(email=email)\n raise ValidationError(message='This email is taken')\n except User.DoesNotExist:\n return email\n\n\ndef email_does_exist(email):\n try:\n User.objects.get(email=email)\n return email\n except User.DoesNotExist:\n raise ValidationError(message='User does not exist!')\n\n\nclass CreatePasswordEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[email_does_exist])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass CreateEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[user_with_email_not_existing])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass EmailSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass EmailValidationSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code']\n\n\nclass EmailValidationPasswordSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n password = serializers.CharField(max_length=200)\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code', 'password']\n\n\nclass NewUserSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):\n\n def validate(self, attrs):\n data = super().validate(attrs)\n refresh = self.get_token(self.user)\n data['refresh'] = str(refresh)\n data['access'] = str(refresh.access_token)\n data['user'] = FullUserSerializer(self.user).data\n return data\n",
"step-4": "<mask token>\nUser = get_user_model()\n\n\ndef user_with_email_not_existing(email):\n try:\n User.objects.get(email=email)\n raise ValidationError(message='This email is taken')\n except User.DoesNotExist:\n return email\n\n\ndef email_does_exist(email):\n try:\n User.objects.get(email=email)\n return email\n except User.DoesNotExist:\n raise ValidationError(message='User does not exist!')\n\n\nclass CreatePasswordEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[email_does_exist])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass CreateEmailValidationSerializer(serializers.Serializer):\n email = serializers.EmailField(validators=[user_with_email_not_existing])\n\n def save(self):\n validation_code = randrange(10000000, 100000000)\n email = Email.objects.create(validation_code=validation_code, to=\n self.validated_data.get('email'), type=self.validated_data.get(\n 'type'))\n new_validation = EmailValidation.objects.create(validation_code=\n validation_code, email=email, type=self.validated_data.get('type'))\n return new_validation\n\n\nclass EmailSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass EmailValidationSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code']\n\n\nclass EmailValidationPasswordSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n password = serializers.CharField(max_length=200)\n\n\n class Meta:\n model = EmailValidation\n fields = ['email', 'validation_code', 'password']\n\n\nclass NewUserSerializer(serializers.ModelSerializer):\n email = serializers.EmailField()\n\n\n class Meta:\n model = EmailValidation\n fields = ['email']\n\n\nclass TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):\n\n def validate(self, attrs):\n data = super().validate(attrs)\n refresh = self.get_token(self.user)\n data['refresh'] = str(refresh)\n data['access'] = str(refresh.access_token)\n data['user'] = FullUserSerializer(self.user).data\n return data\n",
"step-5": "from random import randrange\r\n\r\nfrom django.core.exceptions import ValidationError\r\nfrom django.contrib.auth import get_user_model\r\n\r\nfrom rest_framework import serializers\r\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\r\n\r\nfrom .models import EmailValidation\r\nfrom ..emails.models import Email\r\nfrom ..users.serializers import FullUserSerializer\r\n\r\nUser = get_user_model()\r\n\r\n\r\ndef user_with_email_not_existing(email):\r\n try:\r\n User.objects.get(email=email)\r\n raise ValidationError(message='This email is taken')\r\n except User.DoesNotExist:\r\n return email\r\n\r\n\r\ndef email_does_exist(email):\r\n try:\r\n User.objects.get(email=email)\r\n return email\r\n except User.DoesNotExist:\r\n raise ValidationError(message='User does not exist!')\r\n\r\n\r\nclass CreatePasswordEmailValidationSerializer(serializers.Serializer):\r\n email = serializers.EmailField(validators=[email_does_exist])\r\n\r\n def save(self):\r\n validation_code = randrange(10000000, 100000000)\r\n email = Email.objects.create(\r\n validation_code=validation_code,\r\n to=self.validated_data.get('email'),\r\n type=self.validated_data.get('type')\r\n )\r\n new_validation = EmailValidation.objects.create(\r\n validation_code=validation_code,\r\n email=email,\r\n type=self.validated_data.get('type'))\r\n return new_validation\r\n\r\n\r\nclass CreateEmailValidationSerializer(serializers.Serializer):\r\n email = serializers.EmailField(validators=[user_with_email_not_existing])\r\n\r\n def save(self):\r\n validation_code = randrange(10000000, 100000000)\r\n email = Email.objects.create(\r\n validation_code=validation_code,\r\n to=self.validated_data.get('email'),\r\n type=self.validated_data.get('type')\r\n )\r\n new_validation = EmailValidation.objects.create(\r\n validation_code=validation_code,\r\n email=email,\r\n type=self.validated_data.get('type'))\r\n return new_validation\r\n\r\n\r\nclass EmailSerializer(serializers.ModelSerializer):\r\n email = serializers.EmailField()\r\n\r\n class Meta:\r\n model = EmailValidation\r\n fields = ['email']\r\n\r\n\r\nclass EmailValidationSerializer(serializers.ModelSerializer):\r\n email = serializers.EmailField()\r\n\r\n class Meta:\r\n model = EmailValidation\r\n fields = ['email', 'validation_code']\r\n\r\n\r\nclass EmailValidationPasswordSerializer(serializers.ModelSerializer):\r\n email = serializers.EmailField()\r\n password = serializers.CharField(max_length=200)\r\n\r\n class Meta:\r\n model = EmailValidation\r\n fields = ['email', 'validation_code', 'password']\r\n\r\n\r\nclass NewUserSerializer(serializers.ModelSerializer):\r\n email = serializers.EmailField()\r\n\r\n class Meta:\r\n model = EmailValidation\r\n fields = ['email']\r\n\r\n\r\nclass TokenObtainPairViewWithUserProfileSerializer(TokenObtainPairSerializer):\r\n def validate(self, attrs):\r\n data = super().validate(attrs)\r\n\r\n refresh = self.get_token(self.user)\r\n\r\n data['refresh'] = str(refresh)\r\n data['access'] = str(refresh.access_token)\r\n\r\n data['user'] = FullUserSerializer(self.user).data\r\n return data\r\n",
"step-ids": [
15,
16,
18,
19,
21
]
}
|
[
15,
16,
18,
19,
21
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print('Insert a number')
<|reserved_special_token_0|>
if num1 > 0:
print(f'The square root of {num1} is {math.sqrt(num1)}')
else:
print(f'The square of {num1} is {num1 ** 2}')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print('Insert a number')
num1 = float(input())
if num1 > 0:
print(f'The square root of {num1} is {math.sqrt(num1)}')
else:
print(f'The square of {num1} is {num1 ** 2}')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import math
print('Insert a number')
num1 = float(input())
if num1 > 0:
print(f'The square root of {num1} is {math.sqrt(num1)}')
else:
print(f'The square of {num1} is {num1 ** 2}')
<|reserved_special_token_1|>
"""
Read a real number. If it is positive print it's square root, if it's not print the square of it.
"""
import math
print('Insert a number')
num1 = float(input())
if num1 > 0:
print(f'The square root of {num1} is {math.sqrt(num1)}')
else:
print(f'The square of {num1} is {num1**2}')
|
flexible
|
{
"blob_id": "a68d682ba6d441b9d7fb69ec1ee318a0ef65ed40",
"index": 3146,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('Insert a number')\n<mask token>\nif num1 > 0:\n print(f'The square root of {num1} is {math.sqrt(num1)}')\nelse:\n print(f'The square of {num1} is {num1 ** 2}')\n",
"step-3": "<mask token>\nprint('Insert a number')\nnum1 = float(input())\nif num1 > 0:\n print(f'The square root of {num1} is {math.sqrt(num1)}')\nelse:\n print(f'The square of {num1} is {num1 ** 2}')\n",
"step-4": "<mask token>\nimport math\nprint('Insert a number')\nnum1 = float(input())\nif num1 > 0:\n print(f'The square root of {num1} is {math.sqrt(num1)}')\nelse:\n print(f'The square of {num1} is {num1 ** 2}')\n",
"step-5": "\"\"\"\n\nRead a real number. If it is positive print it's square root, if it's not print the square of it.\n\n\"\"\"\nimport math\n\nprint('Insert a number')\nnum1 = float(input())\n\nif num1 > 0:\n print(f'The square root of {num1} is {math.sqrt(num1)}')\nelse:\n print(f'The square of {num1} is {num1**2}')\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# encoding=utf-8
'''
Finding log2() using sqrt()
原理: sqrt( 2**l * 2**h ) = 2**( (l+h)/2 )
而 a+b /2 正好是binary search, 与sqrt对应上了
题目应当是要求
意思就是找到2**x == y
'''
class Solution:
def log2(self, val):
if 0<val<1: return -self.log2(1.0/val)
if val==1: return 0
h = 1; accuracy = 0.001; cur =2 #val>1 才是普通情况
while cur < val:
h+=1
cur+=cur
l = h-1 #如果是求整数, 已经求得结果了。
lval = cur/2; hval = cur
while l<h:
m = (l+h)/2.0
midVal = (lval * hval)**0.5
if abs(midVal- val)<accuracy: return m
elif midVal> val:
h = m; hval = midVal
else:
l = m; lval = midVal
s = Solution()
print s.log2(13)
|
normal
|
{
"blob_id": "6ea41b0a76ddde04bcaffacea604f218eac9ac71",
"index": 1783,
"step-1": "# encoding=utf-8\n'''\nFinding log2() using sqrt()\n\n\n原理: sqrt( 2**l * 2**h ) = 2**( (l+h)/2 )\n而 a+b /2 正好是binary search, 与sqrt对应上了\n\n题目应当是要求\n\n意思就是找到2**x == y\n'''\n\nclass Solution:\n def log2(self, val):\n if 0<val<1: return -self.log2(1.0/val)\n if val==1: return 0\n h = 1; accuracy = 0.001; cur =2 #val>1 才是普通情况\n while cur < val:\n h+=1\n cur+=cur\n l = h-1 #如果是求整数, 已经求得结果了。\n lval = cur/2; hval = cur\n while l<h:\n m = (l+h)/2.0\n midVal = (lval * hval)**0.5\n if abs(midVal- val)<accuracy: return m\n elif midVal> val:\n h = m; hval = midVal\n else:\n l = m; lval = midVal\ns = Solution()\nprint s.log2(13)\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def __str__(self):
return 'Credentials: ' + self.username + ' - ' + self.password
def login(self):
print('Login done by "%s".' % self.username)
felipe = User(username='felipe', password='pass_user')
print(felipe)
felipe.login()
class Admin(User):
def __init__(self, username, password, phone, email):
super().__init__(username, password)
self.phone = phone
self.email = email
self.user = None
def remove_user_account(self, user):
self.user = user
print(f'%s removeu conta do usuário "%s"' % (self.username, self.
user.username))
def accept_user_account(self, user):
self.user = user
print('%s aceitou conta do usuário "%s"' % (self.username, self.
user.username))
admin = Admin(username='marcos', password='pass_admin', phone='9999-9999',
email='[email protected]')
print(admin)
admin.login()
print(admin.phone)
print(admin.email)
admin.remove_user_account(felipe)
joao = User(username='joao', password='123')
admin.accept_user_account(joao)
|
normal
|
{
"blob_id": "fb26337be29ce06674ca2cb2a82eaff7624aa17f",
"index": 9259,
"step-1": "class User:\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n\n\nclass Admin(User):\n\n def __init__(self, username, password, phone, email):\n super().__init__(username, password)\n self.phone = phone\n self.email = email\n self.user = None\n\n def remove_user_account(self, user):\n self.user = user\n print(f'%s removeu conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n def accept_user_account(self, user):\n self.user = user\n print('%s aceitou conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n\n<mask token>\n",
"step-2": "class User:\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n\n def __str__(self):\n return 'Credentials: ' + self.username + ' - ' + self.password\n\n def login(self):\n print('Login done by \"%s\".' % self.username)\n\n\n<mask token>\n\n\nclass Admin(User):\n\n def __init__(self, username, password, phone, email):\n super().__init__(username, password)\n self.phone = phone\n self.email = email\n self.user = None\n\n def remove_user_account(self, user):\n self.user = user\n print(f'%s removeu conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n def accept_user_account(self, user):\n self.user = user\n print('%s aceitou conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n\n<mask token>\n",
"step-3": "class User:\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n\n def __str__(self):\n return 'Credentials: ' + self.username + ' - ' + self.password\n\n def login(self):\n print('Login done by \"%s\".' % self.username)\n\n\n<mask token>\nprint(felipe)\nfelipe.login()\n\n\nclass Admin(User):\n\n def __init__(self, username, password, phone, email):\n super().__init__(username, password)\n self.phone = phone\n self.email = email\n self.user = None\n\n def remove_user_account(self, user):\n self.user = user\n print(f'%s removeu conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n def accept_user_account(self, user):\n self.user = user\n print('%s aceitou conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n\n<mask token>\nprint(admin)\nadmin.login()\nprint(admin.phone)\nprint(admin.email)\nadmin.remove_user_account(felipe)\n<mask token>\nadmin.accept_user_account(joao)\n",
"step-4": "class User:\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n\n def __str__(self):\n return 'Credentials: ' + self.username + ' - ' + self.password\n\n def login(self):\n print('Login done by \"%s\".' % self.username)\n\n\nfelipe = User(username='felipe', password='pass_user')\nprint(felipe)\nfelipe.login()\n\n\nclass Admin(User):\n\n def __init__(self, username, password, phone, email):\n super().__init__(username, password)\n self.phone = phone\n self.email = email\n self.user = None\n\n def remove_user_account(self, user):\n self.user = user\n print(f'%s removeu conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n def accept_user_account(self, user):\n self.user = user\n print('%s aceitou conta do usuário \"%s\"' % (self.username, self.\n user.username))\n\n\nadmin = Admin(username='marcos', password='pass_admin', phone='9999-9999',\n email='[email protected]')\nprint(admin)\nadmin.login()\nprint(admin.phone)\nprint(admin.email)\nadmin.remove_user_account(felipe)\njoao = User(username='joao', password='123')\nadmin.accept_user_account(joao)\n",
"step-5": null,
"step-ids": [
5,
8,
9,
10
]
}
|
[
5,
8,
9,
10
] |
<|reserved_special_token_0|>
def dataX(features, set):
data_x = np.array([])
count = 0
for filepath in glob.iglob(set):
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
img = Image.open(filepath).convert('L')
data = list(img.getdata())
x = np.array(data)
data_x = np.append(data_x, x)
data_x = data_x.reshape(count, features)
return data_x.astype(int)
def dataY(categories, set):
data_y = np.array([])
count = 0
for filepath in glob.iglob(set):
path = filepath.split('\\')
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
y = np.array([])
t = [int(path[2])]
y = np.append(y, t)
data_y = np.append(data_y, y)
return data_y.astype(int)
def model():
print(' model')
batch_size = 50
features = 32 * 32
categories = 5
filter1 = 32
filter2 = 64
train_path = 'dataset\\train\\[0-4]'
test_path = 'dataset\\test\\[0-4]'
validation_path = 'dataset\\validation\\[0-4]'
data_x = dataX(features, train_path)
print('datax: ', data_x)
data_y = dataY(categories, train_path)
print('datay: ', data_y)
data_x_test = dataX(features, test_path)
data_y_test = dataY(categories, test_path)
data_x_validation = dataX(features, validation_path)
data_y_validation = dataY(categories, validation_path)
x_image = tf.reshape(data_x, [-1, 32, 32, 1])
x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])
x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])
model = models.Sequential()
model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=
'SAME', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=
'SAME', input_shape=(filter1, 16, 16, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(filter2, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(categories))
model.summary()
model.compile(optimizer='adam', loss=tf.keras.losses.
SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(
x_image_validation, data_y_validation))
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)
plt.show()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def next_batch(num, data, labels):
"""
Return a total of `num` random samples and labels.
"""
idx = np.arange(0, len(data))
np.random.shuffle(idx)
idx = idx[:num]
data_shuffle = [data[i] for i in idx]
labels_shuffle = [labels[i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
def dataX(features, set):
data_x = np.array([])
count = 0
for filepath in glob.iglob(set):
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
img = Image.open(filepath).convert('L')
data = list(img.getdata())
x = np.array(data)
data_x = np.append(data_x, x)
data_x = data_x.reshape(count, features)
return data_x.astype(int)
def dataY(categories, set):
data_y = np.array([])
count = 0
for filepath in glob.iglob(set):
path = filepath.split('\\')
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
y = np.array([])
t = [int(path[2])]
y = np.append(y, t)
data_y = np.append(data_y, y)
return data_y.astype(int)
def model():
print(' model')
batch_size = 50
features = 32 * 32
categories = 5
filter1 = 32
filter2 = 64
train_path = 'dataset\\train\\[0-4]'
test_path = 'dataset\\test\\[0-4]'
validation_path = 'dataset\\validation\\[0-4]'
data_x = dataX(features, train_path)
print('datax: ', data_x)
data_y = dataY(categories, train_path)
print('datay: ', data_y)
data_x_test = dataX(features, test_path)
data_y_test = dataY(categories, test_path)
data_x_validation = dataX(features, validation_path)
data_y_validation = dataY(categories, validation_path)
x_image = tf.reshape(data_x, [-1, 32, 32, 1])
x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])
x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])
model = models.Sequential()
model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=
'SAME', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=
'SAME', input_shape=(filter1, 16, 16, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(filter2, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(categories))
model.summary()
model.compile(optimizer='adam', loss=tf.keras.losses.
SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(
x_image_validation, data_y_validation))
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)
plt.show()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def next_batch(num, data, labels):
"""
Return a total of `num` random samples and labels.
"""
idx = np.arange(0, len(data))
np.random.shuffle(idx)
idx = idx[:num]
data_shuffle = [data[i] for i in idx]
labels_shuffle = [labels[i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
def dataX(features, set):
data_x = np.array([])
count = 0
for filepath in glob.iglob(set):
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
img = Image.open(filepath).convert('L')
data = list(img.getdata())
x = np.array(data)
data_x = np.append(data_x, x)
data_x = data_x.reshape(count, features)
return data_x.astype(int)
def dataY(categories, set):
data_y = np.array([])
count = 0
for filepath in glob.iglob(set):
path = filepath.split('\\')
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
y = np.array([])
t = [int(path[2])]
y = np.append(y, t)
data_y = np.append(data_y, y)
return data_y.astype(int)
def model():
print(' model')
batch_size = 50
features = 32 * 32
categories = 5
filter1 = 32
filter2 = 64
train_path = 'dataset\\train\\[0-4]'
test_path = 'dataset\\test\\[0-4]'
validation_path = 'dataset\\validation\\[0-4]'
data_x = dataX(features, train_path)
print('datax: ', data_x)
data_y = dataY(categories, train_path)
print('datay: ', data_y)
data_x_test = dataX(features, test_path)
data_y_test = dataY(categories, test_path)
data_x_validation = dataX(features, validation_path)
data_y_validation = dataY(categories, validation_path)
x_image = tf.reshape(data_x, [-1, 32, 32, 1])
x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])
x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])
model = models.Sequential()
model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=
'SAME', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=
'SAME', input_shape=(filter1, 16, 16, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(filter2, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(categories))
model.summary()
model.compile(optimizer='adam', loss=tf.keras.losses.
SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(
x_image_validation, data_y_validation))
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)
plt.show()
if __name__ == '__main__':
model()
<|reserved_special_token_1|>
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import glob
def next_batch(num, data, labels):
"""
Return a total of `num` random samples and labels.
"""
idx = np.arange(0, len(data))
np.random.shuffle(idx)
idx = idx[:num]
data_shuffle = [data[i] for i in idx]
labels_shuffle = [labels[i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
def dataX(features, set):
data_x = np.array([])
count = 0
for filepath in glob.iglob(set):
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
img = Image.open(filepath).convert('L')
data = list(img.getdata())
x = np.array(data)
data_x = np.append(data_x, x)
data_x = data_x.reshape(count, features)
return data_x.astype(int)
def dataY(categories, set):
data_y = np.array([])
count = 0
for filepath in glob.iglob(set):
path = filepath.split('\\')
globpath = filepath + '\\*.jpg'
for filepath in glob.iglob('' + globpath):
count = count + 1
y = np.array([])
t = [int(path[2])]
y = np.append(y, t)
data_y = np.append(data_y, y)
return data_y.astype(int)
def model():
print(' model')
batch_size = 50
features = 32 * 32
categories = 5
filter1 = 32
filter2 = 64
train_path = 'dataset\\train\\[0-4]'
test_path = 'dataset\\test\\[0-4]'
validation_path = 'dataset\\validation\\[0-4]'
data_x = dataX(features, train_path)
print('datax: ', data_x)
data_y = dataY(categories, train_path)
print('datay: ', data_y)
data_x_test = dataX(features, test_path)
data_y_test = dataY(categories, test_path)
data_x_validation = dataX(features, validation_path)
data_y_validation = dataY(categories, validation_path)
x_image = tf.reshape(data_x, [-1, 32, 32, 1])
x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])
x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])
model = models.Sequential()
model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=
'SAME', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=
'SAME', input_shape=(filter1, 16, 16, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(filter2, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(categories))
model.summary()
model.compile(optimizer='adam', loss=tf.keras.losses.
SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])
history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(
x_image_validation, data_y_validation))
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)
plt.show()
if __name__ == '__main__':
model()
<|reserved_special_token_1|>
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import glob
def next_batch(num, data, labels):
'''
Return a total of `num` random samples and labels.
'''
idx = np.arange(0 , len(data))
np.random.shuffle(idx)
idx = idx[:num]
data_shuffle = [data[ i] for i in idx]
labels_shuffle = [labels[ i] for i in idx]
return np.asarray(data_shuffle), np.asarray(labels_shuffle)
def dataX(features, set):
data_x = np.array([])
count = 0
for filepath in glob.iglob(set):
globpath = filepath + '\*.jpg'
for filepath in glob.iglob(r'' + globpath):
count = count + 1
img = Image.open(filepath).convert('L') # convert image to 8-bit grayscale
data = list(img.getdata())
x = np.array(data)
data_x = np.append(data_x, x)
data_x = data_x.reshape(count, features)
# return data_x
return data_x.astype(int)
def dataY(categories, set):
data_y = np.array([])
count = 0
for filepath in glob.iglob(set):
path = filepath.split("\\")
globpath = filepath + '\*.jpg'
for filepath in glob.iglob(r'' + globpath):
count = count + 1
y = np.array([])
t = [int(path[2])]
y = np.append(y, t)
data_y = np.append(data_y, y)
# data_y = data_y.reshape(count, categories)
# return data_y
return data_y.astype(int)
def model():
print(' model')
batch_size = 50
features = 32 * 32
categories = 5
filter1 = 32
filter2 = 64
train_path = r'dataset\train\[0-4]'
test_path = r'dataset\test\[0-4]'
validation_path = r'dataset\validation\[0-4]'
data_x = dataX(features, train_path)
print("datax: ", data_x)
data_y = dataY(categories, train_path)
print("datay: ", data_y)
data_x_test = dataX(features, test_path)
data_y_test = dataY(categories, test_path)
data_x_validation = dataX(features, validation_path)
data_y_validation = dataY(categories, validation_path)
x_image = tf.reshape(data_x, [-1, 32, 32, 1])
x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])
x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])
model = models.Sequential()
model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding='SAME', input_shape=(32, 32, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding='SAME', input_shape=(filter1, 16, 16, 1)))
model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(filter2, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(categories))
model.summary()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
history = model.fit(x=x_image, y=data_y, epochs=10,
validation_data=(x_image_validation, data_y_validation))
# Show results in graph view
plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label='val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
# plt.show()
test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)
plt.show()
if __name__ == '__main__':
model()
|
flexible
|
{
"blob_id": "f8d815bcdc74452b66a1b3b33bf0fbe976e728c8",
"index": 231,
"step-1": "<mask token>\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of `num` random samples and labels.\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of `num` random samples and labels.\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\nif __name__ == '__main__':\n model()\n",
"step-4": "import tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport glob\n\n\ndef next_batch(num, data, labels):\n \"\"\"\n Return a total of `num` random samples and labels.\n \"\"\"\n idx = np.arange(0, len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[i] for i in idx]\n labels_shuffle = [labels[i] for i in idx]\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L')\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n return data_x.astype(int)\n\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split('\\\\')\n globpath = filepath + '\\\\*.jpg'\n for filepath in glob.iglob('' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n train_path = 'dataset\\\\train\\\\[0-4]'\n test_path = 'dataset\\\\test\\\\[0-4]'\n validation_path = 'dataset\\\\validation\\\\[0-4]'\n data_x = dataX(features, train_path)\n print('datax: ', data_x)\n data_y = dataY(categories, train_path)\n print('datay: ', data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding=\n 'SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n model.summary()\n model.compile(optimizer='adam', loss=tf.keras.losses.\n SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])\n history = model.fit(x=x_image, y=data_y, epochs=10, validation_data=(\n x_image_validation, data_y_validation))\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n plt.show()\n\n\nif __name__ == '__main__':\n model()\n",
"step-5": "# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport tensorflow as tf\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image\nimport glob\n\n\ndef next_batch(num, data, labels):\n '''\n Return a total of `num` random samples and labels.\n '''\n idx = np.arange(0 , len(data))\n np.random.shuffle(idx)\n idx = idx[:num]\n data_shuffle = [data[ i] for i in idx]\n labels_shuffle = [labels[ i] for i in idx]\n\n return np.asarray(data_shuffle), np.asarray(labels_shuffle)\n\ndef dataX(features, set):\n data_x = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n globpath = filepath + '\\*.jpg'\n for filepath in glob.iglob(r'' + globpath):\n count = count + 1\n img = Image.open(filepath).convert('L') # convert image to 8-bit grayscale\n data = list(img.getdata())\n x = np.array(data)\n data_x = np.append(data_x, x)\n data_x = data_x.reshape(count, features)\n # return data_x\n return data_x.astype(int)\n\ndef dataY(categories, set):\n data_y = np.array([])\n count = 0\n for filepath in glob.iglob(set):\n path = filepath.split(\"\\\\\")\n globpath = filepath + '\\*.jpg'\n for filepath in glob.iglob(r'' + globpath):\n count = count + 1\n y = np.array([])\n t = [int(path[2])]\n y = np.append(y, t)\n data_y = np.append(data_y, y)\n # data_y = data_y.reshape(count, categories)\n # return data_y\n return data_y.astype(int)\n\n\ndef model():\n print(' model')\n\n batch_size = 50\n features = 32 * 32\n categories = 5\n filter1 = 32\n filter2 = 64\n\n train_path = r'dataset\\train\\[0-4]'\n test_path = r'dataset\\test\\[0-4]'\n validation_path = r'dataset\\validation\\[0-4]'\n\n\n\n data_x = dataX(features, train_path)\n print(\"datax: \", data_x)\n data_y = dataY(categories, train_path)\n print(\"datay: \", data_y)\n data_x_test = dataX(features, test_path)\n data_y_test = dataY(categories, test_path)\n data_x_validation = dataX(features, validation_path)\n data_y_validation = dataY(categories, validation_path)\n\n x_image = tf.reshape(data_x, [-1, 32, 32, 1])\n x_image_test = tf.reshape(data_x_test, [-1, 32, 32, 1])\n x_image_validation = tf.reshape(data_x_validation, [-1, 32, 32, 1])\n\n model = models.Sequential()\n model.add(layers.Conv2D(filter1, (5, 5), activation='relu', padding='SAME', input_shape=(32, 32, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Conv2D(filter2, (5, 5), activation='relu', padding='SAME', input_shape=(filter1, 16, 16, 1)))\n model.add(layers.MaxPooling2D((2, 2), padding='SAME', strides=(2, 2)))\n model.add(layers.Flatten())\n model.add(layers.Dense(filter2, activation='relu'))\n model.add(layers.Dropout(0.5))\n model.add(layers.Dense(categories))\n\n model.summary()\n\n model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\n history = model.fit(x=x_image, y=data_y, epochs=10,\n validation_data=(x_image_validation, data_y_validation))\n\n # Show results in graph view\n plt.plot(history.history['accuracy'], label='accuracy')\n plt.plot(history.history['val_accuracy'], label='val_accuracy')\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n plt.ylim([0.5, 1])\n plt.legend(loc='lower right')\n # plt.show()\n\n test_loss, test_acc = model.evaluate(x_image_test, data_y_test, verbose=2)\n\n plt.show()\n\nif __name__ == '__main__':\n model()\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
from packet import Packet
from packetConstructor import PacketConstructor
import threading
import time
class PacketSender:
"""
Packet represents a simulated UDP packet.
"""
# The next seq num for sent packets
seq_num = 0
# The next seq num for acks that we're waiting for
next_seq_num = 0
sent_packets = 0
acked_packets = []
acked_all_packets = False
acked_packets_lock = threading.Lock()
was_reset = False
def reset(self):
global seq_num
global sent_packets
global next_seq_num
global acked_packets
global acked_all_packets
global acked_packets_lock
seq_num = 0
sent_packets = 0
next_seq_num = 0
acked_packets = []
acked_all_packets = False
acked_packets_lock = threading.Lock()
def handle_ack(data):
global acked_packets
global seq_num
global acked_all_packets
global acked_packets_lock
p = Packet.from_bytes(data)
if not p.packet_type == PacketConstructor.ack_type:
# TODO: handle NAKs here
return
print("received ack " + str(p.seq_num))
acked_packets_lock.acquire()
if p.seq_num not in acked_packets:
print("it's a new ack")
acked_packets.append(p.seq_num)
if len(acked_packets) == seq_num:
print("got all acks")
acked_all_packets = True
else:
print("len: " + str(len(acked_packets)))
print("seq_num: " + str(seq_num))
acked_packets_lock.release()
def await_acks(conn):
print("awaiting acks")
while not PacketSender.acked_all_packets:
data, sender = conn.recvfrom(1024)
threading.Thread(target=PacketSender.handle_ack, args=(data,)).start()
def resend_packet_if_needed(conn, packet, destination):
while not packet.seq_num in PacketSender.acked_packets and not PacketSender.was_reset:
print("starting resend loop")
time.sleep(0.5)
acked_packets_lock.acquire()
if not packet.seq_num in PacketSender.acked_packets and not PacketSender.was_reset:
print("resending packet " + str(packet.seq_num))
conn.sendto(packet.to_bytes(), destination)
acked_packets_lock.release()
def spawn_resend_thread(conn, packet, destination):
threading.Thread(target=PacketSender.resend_packet_if_needed, args=(conn, packet, destination)).start()
@staticmethod
def send_as_packets(data, conn, destination, peer_ip, peer_port):
global sent_packets
global acked_packets
global next_seq_num
global acked_all_packets
global seq_num
PacketSender.reset()
max_payload_length = Packet.MAX_LEN - Packet.MIN_LEN
curr = [0, 0]
def nbytes(n):
curr[0], curr[1] = curr[1], curr[1] + n
return data[curr[0]: curr[1]]
remaining_data = len(data)
if remaining_data > 0:
threading.Thread(target=PacketSender.await_acks, args=(conn,)).start()
# While there's still data to be sent
while remaining_data > 0:
# While there are less packets in transit than the window size
while (sent_packets < PacketConstructor.window_size and remaining_data > 0):
print("sending packet %d" % seq_num)
if remaining_data > max_payload_length:
p = Packet(packet_type=PacketConstructor.data_type,
seq_num=seq_num,
peer_ip_addr=peer_ip,
peer_port=peer_port,
is_last_packet=False,
payload=nbytes(max_payload_length))
conn.sendto(p.to_bytes(), destination)
sent_packets += 1
remaining_data -= max_payload_length
seq_num += 1
PacketSender.spawn_resend_thread(conn, p, destination)
print("not last packet")
else:
p = Packet(packet_type=PacketConstructor.data_type,
seq_num=seq_num,
peer_ip_addr=peer_ip,
peer_port=peer_port,
is_last_packet=True,
payload=nbytes(remaining_data))
conn.sendto(p.to_bytes(), destination)
sent_packets += 1
remaining_data -= remaining_data
seq_num += 1
print("remaining data " + str(remaining_data))
print("is last packet")
PacketSender.spawn_resend_thread(conn, p, destination)
# Update the number of packets still in transit
while next_seq_num in acked_packets:
next_seq_num += 1
sent_packets -= 1
print("Waiting for acks")
while not acked_all_packets:
# Wait here until all packets have been acked
pass
print("RECEIVED ALL ACKS")
PacketSender.was_reset = True
|
normal
|
{
"blob_id": "47c1ad4bd1ceffa38eef467ea8eb59dbd2fc2ebb",
"index": 262,
"step-1": "<mask token>\n\n\nclass PacketSender:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def await_acks(conn):\n print('awaiting acks')\n while not PacketSender.acked_all_packets:\n data, sender = conn.recvfrom(1024)\n threading.Thread(target=PacketSender.handle_ack, args=(data,)\n ).start()\n <mask token>\n <mask token>\n\n @staticmethod\n def send_as_packets(data, conn, destination, peer_ip, peer_port):\n global sent_packets\n global acked_packets\n global next_seq_num\n global acked_all_packets\n global seq_num\n PacketSender.reset()\n max_payload_length = Packet.MAX_LEN - Packet.MIN_LEN\n curr = [0, 0]\n\n def nbytes(n):\n curr[0], curr[1] = curr[1], curr[1] + n\n return data[curr[0]:curr[1]]\n remaining_data = len(data)\n if remaining_data > 0:\n threading.Thread(target=PacketSender.await_acks, args=(conn,)\n ).start()\n while remaining_data > 0:\n while (sent_packets < PacketConstructor.window_size and \n remaining_data > 0):\n print('sending packet %d' % seq_num)\n if remaining_data > max_payload_length:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=False, payload=nbytes(\n max_payload_length))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= max_payload_length\n seq_num += 1\n PacketSender.spawn_resend_thread(conn, p, destination)\n print('not last packet')\n else:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=True, payload=nbytes(\n remaining_data))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= remaining_data\n seq_num += 1\n print('remaining data ' + str(remaining_data))\n print('is last packet')\n PacketSender.spawn_resend_thread(conn, p, destination)\n while next_seq_num in acked_packets:\n next_seq_num += 1\n sent_packets -= 1\n print('Waiting for acks')\n while not acked_all_packets:\n pass\n print('RECEIVED ALL ACKS')\n PacketSender.was_reset = True\n",
"step-2": "<mask token>\n\n\nclass PacketSender:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def reset(self):\n global seq_num\n global sent_packets\n global next_seq_num\n global acked_packets\n global acked_all_packets\n global acked_packets_lock\n seq_num = 0\n sent_packets = 0\n next_seq_num = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n\n def handle_ack(data):\n global acked_packets\n global seq_num\n global acked_all_packets\n global acked_packets_lock\n p = Packet.from_bytes(data)\n if not p.packet_type == PacketConstructor.ack_type:\n return\n print('received ack ' + str(p.seq_num))\n acked_packets_lock.acquire()\n if p.seq_num not in acked_packets:\n print(\"it's a new ack\")\n acked_packets.append(p.seq_num)\n if len(acked_packets) == seq_num:\n print('got all acks')\n acked_all_packets = True\n else:\n print('len: ' + str(len(acked_packets)))\n print('seq_num: ' + str(seq_num))\n acked_packets_lock.release()\n\n def await_acks(conn):\n print('awaiting acks')\n while not PacketSender.acked_all_packets:\n data, sender = conn.recvfrom(1024)\n threading.Thread(target=PacketSender.handle_ack, args=(data,)\n ).start()\n <mask token>\n <mask token>\n\n @staticmethod\n def send_as_packets(data, conn, destination, peer_ip, peer_port):\n global sent_packets\n global acked_packets\n global next_seq_num\n global acked_all_packets\n global seq_num\n PacketSender.reset()\n max_payload_length = Packet.MAX_LEN - Packet.MIN_LEN\n curr = [0, 0]\n\n def nbytes(n):\n curr[0], curr[1] = curr[1], curr[1] + n\n return data[curr[0]:curr[1]]\n remaining_data = len(data)\n if remaining_data > 0:\n threading.Thread(target=PacketSender.await_acks, args=(conn,)\n ).start()\n while remaining_data > 0:\n while (sent_packets < PacketConstructor.window_size and \n remaining_data > 0):\n print('sending packet %d' % seq_num)\n if remaining_data > max_payload_length:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=False, payload=nbytes(\n max_payload_length))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= max_payload_length\n seq_num += 1\n PacketSender.spawn_resend_thread(conn, p, destination)\n print('not last packet')\n else:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=True, payload=nbytes(\n remaining_data))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= remaining_data\n seq_num += 1\n print('remaining data ' + str(remaining_data))\n print('is last packet')\n PacketSender.spawn_resend_thread(conn, p, destination)\n while next_seq_num in acked_packets:\n next_seq_num += 1\n sent_packets -= 1\n print('Waiting for acks')\n while not acked_all_packets:\n pass\n print('RECEIVED ALL ACKS')\n PacketSender.was_reset = True\n",
"step-3": "<mask token>\n\n\nclass PacketSender:\n \"\"\"\n Packet represents a simulated UDP packet.\n \"\"\"\n seq_num = 0\n next_seq_num = 0\n sent_packets = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n was_reset = False\n\n def reset(self):\n global seq_num\n global sent_packets\n global next_seq_num\n global acked_packets\n global acked_all_packets\n global acked_packets_lock\n seq_num = 0\n sent_packets = 0\n next_seq_num = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n\n def handle_ack(data):\n global acked_packets\n global seq_num\n global acked_all_packets\n global acked_packets_lock\n p = Packet.from_bytes(data)\n if not p.packet_type == PacketConstructor.ack_type:\n return\n print('received ack ' + str(p.seq_num))\n acked_packets_lock.acquire()\n if p.seq_num not in acked_packets:\n print(\"it's a new ack\")\n acked_packets.append(p.seq_num)\n if len(acked_packets) == seq_num:\n print('got all acks')\n acked_all_packets = True\n else:\n print('len: ' + str(len(acked_packets)))\n print('seq_num: ' + str(seq_num))\n acked_packets_lock.release()\n\n def await_acks(conn):\n print('awaiting acks')\n while not PacketSender.acked_all_packets:\n data, sender = conn.recvfrom(1024)\n threading.Thread(target=PacketSender.handle_ack, args=(data,)\n ).start()\n\n def resend_packet_if_needed(conn, packet, destination):\n while (not packet.seq_num in PacketSender.acked_packets and not\n PacketSender.was_reset):\n print('starting resend loop')\n time.sleep(0.5)\n acked_packets_lock.acquire()\n if (not packet.seq_num in PacketSender.acked_packets and not\n PacketSender.was_reset):\n print('resending packet ' + str(packet.seq_num))\n conn.sendto(packet.to_bytes(), destination)\n acked_packets_lock.release()\n\n def spawn_resend_thread(conn, packet, destination):\n threading.Thread(target=PacketSender.resend_packet_if_needed, args=\n (conn, packet, destination)).start()\n\n @staticmethod\n def send_as_packets(data, conn, destination, peer_ip, peer_port):\n global sent_packets\n global acked_packets\n global next_seq_num\n global acked_all_packets\n global seq_num\n PacketSender.reset()\n max_payload_length = Packet.MAX_LEN - Packet.MIN_LEN\n curr = [0, 0]\n\n def nbytes(n):\n curr[0], curr[1] = curr[1], curr[1] + n\n return data[curr[0]:curr[1]]\n remaining_data = len(data)\n if remaining_data > 0:\n threading.Thread(target=PacketSender.await_acks, args=(conn,)\n ).start()\n while remaining_data > 0:\n while (sent_packets < PacketConstructor.window_size and \n remaining_data > 0):\n print('sending packet %d' % seq_num)\n if remaining_data > max_payload_length:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=False, payload=nbytes(\n max_payload_length))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= max_payload_length\n seq_num += 1\n PacketSender.spawn_resend_thread(conn, p, destination)\n print('not last packet')\n else:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=True, payload=nbytes(\n remaining_data))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= remaining_data\n seq_num += 1\n print('remaining data ' + str(remaining_data))\n print('is last packet')\n PacketSender.spawn_resend_thread(conn, p, destination)\n while next_seq_num in acked_packets:\n next_seq_num += 1\n sent_packets -= 1\n print('Waiting for acks')\n while not acked_all_packets:\n pass\n print('RECEIVED ALL ACKS')\n PacketSender.was_reset = True\n",
"step-4": "from packet import Packet\nfrom packetConstructor import PacketConstructor\nimport threading\nimport time\n\n\nclass PacketSender:\n \"\"\"\n Packet represents a simulated UDP packet.\n \"\"\"\n seq_num = 0\n next_seq_num = 0\n sent_packets = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n was_reset = False\n\n def reset(self):\n global seq_num\n global sent_packets\n global next_seq_num\n global acked_packets\n global acked_all_packets\n global acked_packets_lock\n seq_num = 0\n sent_packets = 0\n next_seq_num = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n\n def handle_ack(data):\n global acked_packets\n global seq_num\n global acked_all_packets\n global acked_packets_lock\n p = Packet.from_bytes(data)\n if not p.packet_type == PacketConstructor.ack_type:\n return\n print('received ack ' + str(p.seq_num))\n acked_packets_lock.acquire()\n if p.seq_num not in acked_packets:\n print(\"it's a new ack\")\n acked_packets.append(p.seq_num)\n if len(acked_packets) == seq_num:\n print('got all acks')\n acked_all_packets = True\n else:\n print('len: ' + str(len(acked_packets)))\n print('seq_num: ' + str(seq_num))\n acked_packets_lock.release()\n\n def await_acks(conn):\n print('awaiting acks')\n while not PacketSender.acked_all_packets:\n data, sender = conn.recvfrom(1024)\n threading.Thread(target=PacketSender.handle_ack, args=(data,)\n ).start()\n\n def resend_packet_if_needed(conn, packet, destination):\n while (not packet.seq_num in PacketSender.acked_packets and not\n PacketSender.was_reset):\n print('starting resend loop')\n time.sleep(0.5)\n acked_packets_lock.acquire()\n if (not packet.seq_num in PacketSender.acked_packets and not\n PacketSender.was_reset):\n print('resending packet ' + str(packet.seq_num))\n conn.sendto(packet.to_bytes(), destination)\n acked_packets_lock.release()\n\n def spawn_resend_thread(conn, packet, destination):\n threading.Thread(target=PacketSender.resend_packet_if_needed, args=\n (conn, packet, destination)).start()\n\n @staticmethod\n def send_as_packets(data, conn, destination, peer_ip, peer_port):\n global sent_packets\n global acked_packets\n global next_seq_num\n global acked_all_packets\n global seq_num\n PacketSender.reset()\n max_payload_length = Packet.MAX_LEN - Packet.MIN_LEN\n curr = [0, 0]\n\n def nbytes(n):\n curr[0], curr[1] = curr[1], curr[1] + n\n return data[curr[0]:curr[1]]\n remaining_data = len(data)\n if remaining_data > 0:\n threading.Thread(target=PacketSender.await_acks, args=(conn,)\n ).start()\n while remaining_data > 0:\n while (sent_packets < PacketConstructor.window_size and \n remaining_data > 0):\n print('sending packet %d' % seq_num)\n if remaining_data > max_payload_length:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=False, payload=nbytes(\n max_payload_length))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= max_payload_length\n seq_num += 1\n PacketSender.spawn_resend_thread(conn, p, destination)\n print('not last packet')\n else:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num, peer_ip_addr=peer_ip, peer_port=\n peer_port, is_last_packet=True, payload=nbytes(\n remaining_data))\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= remaining_data\n seq_num += 1\n print('remaining data ' + str(remaining_data))\n print('is last packet')\n PacketSender.spawn_resend_thread(conn, p, destination)\n while next_seq_num in acked_packets:\n next_seq_num += 1\n sent_packets -= 1\n print('Waiting for acks')\n while not acked_all_packets:\n pass\n print('RECEIVED ALL ACKS')\n PacketSender.was_reset = True\n",
"step-5": "from packet import Packet\nfrom packetConstructor import PacketConstructor\nimport threading\nimport time\n\n\nclass PacketSender:\n \"\"\"\n Packet represents a simulated UDP packet.\n \"\"\"\n # The next seq num for sent packets\n seq_num = 0\n # The next seq num for acks that we're waiting for\n next_seq_num = 0\n sent_packets = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n was_reset = False\n\n def reset(self):\n global seq_num\n global sent_packets\n global next_seq_num\n global acked_packets\n global acked_all_packets\n global acked_packets_lock\n seq_num = 0\n sent_packets = 0\n next_seq_num = 0\n acked_packets = []\n acked_all_packets = False\n acked_packets_lock = threading.Lock()\n\n def handle_ack(data):\n global acked_packets\n global seq_num\n global acked_all_packets\n global acked_packets_lock\n p = Packet.from_bytes(data)\n if not p.packet_type == PacketConstructor.ack_type:\n # TODO: handle NAKs here\n return\n print(\"received ack \" + str(p.seq_num))\n acked_packets_lock.acquire()\n if p.seq_num not in acked_packets:\n print(\"it's a new ack\")\n acked_packets.append(p.seq_num)\n if len(acked_packets) == seq_num:\n print(\"got all acks\")\n acked_all_packets = True\n else:\n print(\"len: \" + str(len(acked_packets)))\n print(\"seq_num: \" + str(seq_num))\n acked_packets_lock.release()\n\n def await_acks(conn):\n print(\"awaiting acks\")\n while not PacketSender.acked_all_packets:\n data, sender = conn.recvfrom(1024)\n threading.Thread(target=PacketSender.handle_ack, args=(data,)).start()\n\n def resend_packet_if_needed(conn, packet, destination):\n while not packet.seq_num in PacketSender.acked_packets and not PacketSender.was_reset:\n print(\"starting resend loop\")\n time.sleep(0.5)\n acked_packets_lock.acquire()\n if not packet.seq_num in PacketSender.acked_packets and not PacketSender.was_reset:\n print(\"resending packet \" + str(packet.seq_num))\n conn.sendto(packet.to_bytes(), destination)\n acked_packets_lock.release()\n\n def spawn_resend_thread(conn, packet, destination):\n threading.Thread(target=PacketSender.resend_packet_if_needed, args=(conn, packet, destination)).start()\n\n @staticmethod\n def send_as_packets(data, conn, destination, peer_ip, peer_port):\n global sent_packets\n global acked_packets\n global next_seq_num\n global acked_all_packets\n global seq_num\n PacketSender.reset()\n max_payload_length = Packet.MAX_LEN - Packet.MIN_LEN\n\n curr = [0, 0]\n\n def nbytes(n):\n curr[0], curr[1] = curr[1], curr[1] + n\n return data[curr[0]: curr[1]]\n\n remaining_data = len(data)\n if remaining_data > 0:\n threading.Thread(target=PacketSender.await_acks, args=(conn,)).start()\n # While there's still data to be sent\n while remaining_data > 0:\n # While there are less packets in transit than the window size\n while (sent_packets < PacketConstructor.window_size and remaining_data > 0):\n print(\"sending packet %d\" % seq_num)\n if remaining_data > max_payload_length:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num,\n peer_ip_addr=peer_ip,\n peer_port=peer_port,\n is_last_packet=False,\n payload=nbytes(max_payload_length))\n\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= max_payload_length\n seq_num += 1\n PacketSender.spawn_resend_thread(conn, p, destination)\n print(\"not last packet\")\n else:\n p = Packet(packet_type=PacketConstructor.data_type,\n seq_num=seq_num,\n peer_ip_addr=peer_ip,\n peer_port=peer_port,\n is_last_packet=True,\n payload=nbytes(remaining_data))\n\n conn.sendto(p.to_bytes(), destination)\n sent_packets += 1\n remaining_data -= remaining_data\n seq_num += 1\n print(\"remaining data \" + str(remaining_data))\n print(\"is last packet\")\n PacketSender.spawn_resend_thread(conn, p, destination)\n # Update the number of packets still in transit\n while next_seq_num in acked_packets:\n next_seq_num += 1\n sent_packets -= 1\n print(\"Waiting for acks\")\n while not acked_all_packets:\n # Wait here until all packets have been acked\n pass\n print(\"RECEIVED ALL ACKS\")\n PacketSender.was_reset = True\n",
"step-ids": [
3,
5,
9,
10,
11
]
}
|
[
3,
5,
9,
10,
11
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# sockdemo.py
#
# test
import struct, threading, signal
a = ''
if not a:
print 'a'
else:
print 'b'
import datetime, time, os
print datetime.datetime.now().strftime('%m-%d %H:%M:%S')
def double(x): return x*x
arr = [1, 2, 3, 4, 5]
print map(double, arr)
print 2**16
print struct.calcsize('128s32sI8s')
_pack = struct.pack('128s8sI8s','abc','huad',1,'666')
print repr(_pack)
a,b,c,d = struct.unpack('128s8sI8s',_pack)
print a.strip('\00')
now = datetime.datetime.now()
isstop = False
def handler():
print 'control C'
isstop = True
def doStress():
print 123222
while not isstop:
time.sleep(1)
print 'doStress', datetime.datetime.now()
#signal.signal(signal.SIGINT, handler)
#signal.signal(signal.SIGTERM, handler)
t = threading.Thread(target=doStress, args=())
t.setDaemon(True)
t.start()
print 'complete', datetime.datetime.now()
|
normal
|
{
"blob_id": "54d6121898dc027d6ecaf9c9e7c25391778e0d21",
"index": 7311,
"step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# sockdemo.py\n#\n# test\n\nimport struct, threading, signal\n\na = ''\n\nif not a:\n\tprint 'a'\nelse:\n\tprint 'b'\n\nimport datetime, time, os\n\nprint datetime.datetime.now().strftime('%m-%d %H:%M:%S')\n\ndef double(x): return x*x\n\narr = [1, 2, 3, 4, 5]\nprint map(double, arr)\nprint 2**16\nprint struct.calcsize('128s32sI8s')\n\n_pack = struct.pack('128s8sI8s','abc','huad',1,'666')\nprint repr(_pack)\na,b,c,d = struct.unpack('128s8sI8s',_pack)\nprint a.strip('\\00')\n\nnow = datetime.datetime.now()\n\nisstop = False\n\ndef handler():\n\tprint 'control C'\n\tisstop = True\n\ndef doStress():\n\tprint 123222\n\twhile not isstop:\n\t\ttime.sleep(1)\n\t\tprint 'doStress', datetime.datetime.now()\n\n#signal.signal(signal.SIGINT, handler)\n#signal.signal(signal.SIGTERM, handler)\n\nt = threading.Thread(target=doStress, args=())\nt.setDaemon(True)\nt.start()\nprint 'complete', datetime.datetime.now()\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
# Write function that determines if a string a palindrome off of any permutation
def palinPerm(str):
# Create empty set
charSet = set()
# Loop through string, if character does not exist in set, add it. If it does, remove it.
for c in str:
if c not in charSet:
charSet.add(c)
else:
charSet.remove(c)
# The final set should either have 1 element or none
return len(charSet) == 1 or len(charSet) == 0
response = "It is a palinPerm" if palinPerm("dadadad") else "No, not a palinPerm"
print(response)
# Time Complexity: O(N)
|
normal
|
{
"blob_id": "04487dce97231a7be2bf3b164e93f0ea4d01ba05",
"index": 1160,
"step-1": "<mask token>\n",
"step-2": "def palinPerm(str):\n charSet = set()\n for c in str:\n if c not in charSet:\n charSet.add(c)\n else:\n charSet.remove(c)\n return len(charSet) == 1 or len(charSet) == 0\n\n\n<mask token>\n",
"step-3": "def palinPerm(str):\n charSet = set()\n for c in str:\n if c not in charSet:\n charSet.add(c)\n else:\n charSet.remove(c)\n return len(charSet) == 1 or len(charSet) == 0\n\n\n<mask token>\nprint(response)\n",
"step-4": "def palinPerm(str):\n charSet = set()\n for c in str:\n if c not in charSet:\n charSet.add(c)\n else:\n charSet.remove(c)\n return len(charSet) == 1 or len(charSet) == 0\n\n\nresponse = 'It is a palinPerm' if palinPerm('dadadad'\n ) else 'No, not a palinPerm'\nprint(response)\n",
"step-5": "# Write function that determines if a string a palindrome off of any permutation\ndef palinPerm(str):\n # Create empty set\n charSet = set()\n\n # Loop through string, if character does not exist in set, add it. If it does, remove it.\n for c in str:\n if c not in charSet:\n charSet.add(c)\n else:\n charSet.remove(c)\n\n # The final set should either have 1 element or none\n return len(charSet) == 1 or len(charSet) == 0\n\n\nresponse = \"It is a palinPerm\" if palinPerm(\"dadadad\") else \"No, not a palinPerm\"\nprint(response)\n\n# Time Complexity: O(N)",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import sys
import queue as q
from utils import *
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lines = sys.stdin.readlines()
i_max = len(lines)
j_max = len(lines[0])
deltas = [
((0, 0), (0, 1), (0, 2)),
((0, 1), (0, 2), (0, 0)),
((0, 0), (1, 0), (2, 0)),
((1, 0), (2, 0), (0, 0)),
]
portals = {}
for i in range(i_max - 2):
for j in range(j_max - 2):
for d in deltas:
if (lines[i+d[0][0]][j+d[0][1]] in LETTERS and
lines[i+d[1][0]][j+d[1][1]] in LETTERS and
lines[i+d[2][0]][j+d[2][1]] == '.'):
portal = lines[i+d[0][0]][j+d[0][1]] + lines[i+d[1][0]][j+d[1][1]]
this_end = (i+d[2][0], j+d[2][1])
if portal in portals:
other_end = portals.pop(portal)
portals[this_end] = other_end
portals[other_end] = this_end
else:
portals[portal] = this_end
# Part I
distance = {}
def nextsteps(point):
for ns in nextsteps2d(point):
yield ns
if point in portals:
yield portals[point]
def should_visit(point):
return lines[point[0]][point[1]] == '.'
part1 = bfs_visited(
origin=portals['AA'],
should_visit=should_visit,
nextsteps=nextsteps,
destination=portals['ZZ'])
print(part1)
# Part II
i, j = portals['AA']
origin = (i, j, 0)
i, j = portals['ZZ']
destination = (i, j, 0)
def nextsteps_with_recursion(point):
i, j, level = point
for i1, j1 in nextsteps2d((i, j)):
yield (i1, j1, level)
if (i, j) in portals:
if i == 2 or j == 2 or i == i_max - 3 or j == j_max - 4:
if level > 0:
i, j = portals[i, j]
yield (i, j, level-1)
else:
i, j = portals[i, j]
yield (i, j, level+1)
part2 = bfs_visited(
origin=origin,
should_visit=should_visit,
nextsteps=nextsteps_with_recursion,
destination=destination)
print(part2)
|
normal
|
{
"blob_id": "973fc3a973d952cb0f192221dfda63e255e4a8a0",
"index": 2543,
"step-1": "<mask token>\n\n\ndef nextsteps(point):\n for ns in nextsteps2d(point):\n yield ns\n if point in portals:\n yield portals[point]\n\n\ndef should_visit(point):\n return lines[point[0]][point[1]] == '.'\n\n\n<mask token>\n\n\ndef nextsteps_with_recursion(point):\n i, j, level = point\n for i1, j1 in nextsteps2d((i, j)):\n yield i1, j1, level\n if (i, j) in portals:\n if i == 2 or j == 2 or i == i_max - 3 or j == j_max - 4:\n if level > 0:\n i, j = portals[i, j]\n yield i, j, level - 1\n else:\n i, j = portals[i, j]\n yield i, j, level + 1\n\n\n<mask token>\n",
"step-2": "<mask token>\nfor i in range(i_max - 2):\n for j in range(j_max - 2):\n for d in deltas:\n if lines[i + d[0][0]][j + d[0][1]] in LETTERS and lines[i + d[1][0]\n ][j + d[1][1]] in LETTERS and lines[i + d[2][0]][j + d[2][1]\n ] == '.':\n portal = lines[i + d[0][0]][j + d[0][1]] + lines[i + d[1][0]][\n j + d[1][1]]\n this_end = i + d[2][0], j + d[2][1]\n if portal in portals:\n other_end = portals.pop(portal)\n portals[this_end] = other_end\n portals[other_end] = this_end\n else:\n portals[portal] = this_end\n<mask token>\n\n\ndef nextsteps(point):\n for ns in nextsteps2d(point):\n yield ns\n if point in portals:\n yield portals[point]\n\n\ndef should_visit(point):\n return lines[point[0]][point[1]] == '.'\n\n\n<mask token>\nprint(part1)\n<mask token>\n\n\ndef nextsteps_with_recursion(point):\n i, j, level = point\n for i1, j1 in nextsteps2d((i, j)):\n yield i1, j1, level\n if (i, j) in portals:\n if i == 2 or j == 2 or i == i_max - 3 or j == j_max - 4:\n if level > 0:\n i, j = portals[i, j]\n yield i, j, level - 1\n else:\n i, j = portals[i, j]\n yield i, j, level + 1\n\n\n<mask token>\nprint(part2)\n",
"step-3": "<mask token>\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nlines = sys.stdin.readlines()\ni_max = len(lines)\nj_max = len(lines[0])\ndeltas = [((0, 0), (0, 1), (0, 2)), ((0, 1), (0, 2), (0, 0)), ((0, 0), (1, \n 0), (2, 0)), ((1, 0), (2, 0), (0, 0))]\nportals = {}\nfor i in range(i_max - 2):\n for j in range(j_max - 2):\n for d in deltas:\n if lines[i + d[0][0]][j + d[0][1]] in LETTERS and lines[i + d[1][0]\n ][j + d[1][1]] in LETTERS and lines[i + d[2][0]][j + d[2][1]\n ] == '.':\n portal = lines[i + d[0][0]][j + d[0][1]] + lines[i + d[1][0]][\n j + d[1][1]]\n this_end = i + d[2][0], j + d[2][1]\n if portal in portals:\n other_end = portals.pop(portal)\n portals[this_end] = other_end\n portals[other_end] = this_end\n else:\n portals[portal] = this_end\ndistance = {}\n\n\ndef nextsteps(point):\n for ns in nextsteps2d(point):\n yield ns\n if point in portals:\n yield portals[point]\n\n\ndef should_visit(point):\n return lines[point[0]][point[1]] == '.'\n\n\npart1 = bfs_visited(origin=portals['AA'], should_visit=should_visit,\n nextsteps=nextsteps, destination=portals['ZZ'])\nprint(part1)\ni, j = portals['AA']\norigin = i, j, 0\ni, j = portals['ZZ']\ndestination = i, j, 0\n\n\ndef nextsteps_with_recursion(point):\n i, j, level = point\n for i1, j1 in nextsteps2d((i, j)):\n yield i1, j1, level\n if (i, j) in portals:\n if i == 2 or j == 2 or i == i_max - 3 or j == j_max - 4:\n if level > 0:\n i, j = portals[i, j]\n yield i, j, level - 1\n else:\n i, j = portals[i, j]\n yield i, j, level + 1\n\n\npart2 = bfs_visited(origin=origin, should_visit=should_visit, nextsteps=\n nextsteps_with_recursion, destination=destination)\nprint(part2)\n",
"step-4": "import sys\nimport queue as q\nfrom utils import *\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\nlines = sys.stdin.readlines()\ni_max = len(lines)\nj_max = len(lines[0])\ndeltas = [((0, 0), (0, 1), (0, 2)), ((0, 1), (0, 2), (0, 0)), ((0, 0), (1, \n 0), (2, 0)), ((1, 0), (2, 0), (0, 0))]\nportals = {}\nfor i in range(i_max - 2):\n for j in range(j_max - 2):\n for d in deltas:\n if lines[i + d[0][0]][j + d[0][1]] in LETTERS and lines[i + d[1][0]\n ][j + d[1][1]] in LETTERS and lines[i + d[2][0]][j + d[2][1]\n ] == '.':\n portal = lines[i + d[0][0]][j + d[0][1]] + lines[i + d[1][0]][\n j + d[1][1]]\n this_end = i + d[2][0], j + d[2][1]\n if portal in portals:\n other_end = portals.pop(portal)\n portals[this_end] = other_end\n portals[other_end] = this_end\n else:\n portals[portal] = this_end\ndistance = {}\n\n\ndef nextsteps(point):\n for ns in nextsteps2d(point):\n yield ns\n if point in portals:\n yield portals[point]\n\n\ndef should_visit(point):\n return lines[point[0]][point[1]] == '.'\n\n\npart1 = bfs_visited(origin=portals['AA'], should_visit=should_visit,\n nextsteps=nextsteps, destination=portals['ZZ'])\nprint(part1)\ni, j = portals['AA']\norigin = i, j, 0\ni, j = portals['ZZ']\ndestination = i, j, 0\n\n\ndef nextsteps_with_recursion(point):\n i, j, level = point\n for i1, j1 in nextsteps2d((i, j)):\n yield i1, j1, level\n if (i, j) in portals:\n if i == 2 or j == 2 or i == i_max - 3 or j == j_max - 4:\n if level > 0:\n i, j = portals[i, j]\n yield i, j, level - 1\n else:\n i, j = portals[i, j]\n yield i, j, level + 1\n\n\npart2 = bfs_visited(origin=origin, should_visit=should_visit, nextsteps=\n nextsteps_with_recursion, destination=destination)\nprint(part2)\n",
"step-5": "import sys\nimport queue as q\nfrom utils import *\n\nLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\nlines = sys.stdin.readlines()\ni_max = len(lines)\nj_max = len(lines[0])\n\ndeltas = [\n ((0, 0), (0, 1), (0, 2)),\n ((0, 1), (0, 2), (0, 0)),\n ((0, 0), (1, 0), (2, 0)),\n ((1, 0), (2, 0), (0, 0)),\n ]\nportals = {}\nfor i in range(i_max - 2):\n for j in range(j_max - 2):\n for d in deltas:\n if (lines[i+d[0][0]][j+d[0][1]] in LETTERS and\n lines[i+d[1][0]][j+d[1][1]] in LETTERS and\n lines[i+d[2][0]][j+d[2][1]] == '.'):\n portal = lines[i+d[0][0]][j+d[0][1]] + lines[i+d[1][0]][j+d[1][1]]\n this_end = (i+d[2][0], j+d[2][1])\n if portal in portals:\n other_end = portals.pop(portal)\n portals[this_end] = other_end\n portals[other_end] = this_end\n else:\n portals[portal] = this_end\n\n\n# Part I\ndistance = {}\n\ndef nextsteps(point):\n for ns in nextsteps2d(point):\n yield ns\n if point in portals:\n yield portals[point]\n\n\ndef should_visit(point):\n return lines[point[0]][point[1]] == '.'\n\n\npart1 = bfs_visited(\n origin=portals['AA'],\n should_visit=should_visit,\n nextsteps=nextsteps,\n destination=portals['ZZ'])\n\nprint(part1)\n\n\n# Part II\ni, j = portals['AA']\norigin = (i, j, 0)\ni, j = portals['ZZ']\ndestination = (i, j, 0)\n\ndef nextsteps_with_recursion(point):\n i, j, level = point\n for i1, j1 in nextsteps2d((i, j)):\n yield (i1, j1, level)\n if (i, j) in portals:\n if i == 2 or j == 2 or i == i_max - 3 or j == j_max - 4:\n if level > 0:\n i, j = portals[i, j]\n yield (i, j, level-1)\n else:\n i, j = portals[i, j]\n yield (i, j, level+1)\n \n\n\npart2 = bfs_visited(\n origin=origin,\n should_visit=should_visit,\n nextsteps=nextsteps_with_recursion,\n destination=destination)\n\nprint(part2)\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
class CodeGenerator:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, tree, file=sys.stdout):
"""CodeGenerator(tree, file=sys.stdout) -> None.
Print the source for tree to file."""
self.f = file
self.future_imports = []
self._indent = 0
self._locals = ['pyflamegpu']
self._device_functions = []
self._message_iterator_var = None
self._input_message_var = 'message_in'
self._output_message_var = 'message_out'
self.dispatch(tree)
print('', file=self.f)
self.f.flush()
<|reserved_special_token_0|>
def fill(self, text=''):
"""Indent a piece of text, according to the current indentation level"""
self.f.write('\n' + ' ' * self._indent + text)
<|reserved_special_token_0|>
def enter(self):
"""Print '{', and increase the indentation."""
self.write('{')
self._indent += 1
def leave(self):
"""Decrease the indentation level and Print '}'"""
self._indent -= 1
self.fill('}')
<|reserved_special_token_0|>
def RaiseWarning(self, tree, str):
warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')
def RaiseError(self, tree, str):
raise CodeGenException(
f'Error ({tree.lineno}, {tree.col_offset}): {str}')
<|reserved_special_token_0|>
def dispatchFGPUFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`
Type hinting is required to translate a type into a FLAME GPU Message type implementation
"""
self._locals = ['pyflamegpu']
if len(tree.args.args) != 2:
self.RaiseError(tree,
'Expected two FLAME GPU function arguments (input message and output message)'
)
if not tree.args.args[0].annotation:
self.RaiseError(tree.args.args[0],
'Message input requires a supported type annotation')
if not isinstance(tree.args.args[0].annotation, ast.Attribute):
self.RaiseError(tree.args.args[0],
'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[0].annotation.value, ast.Name):
self.RaiseError(tree.args.args[0],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
input_message_attr = tree.args.args[0
].annotation.value.id + '.' + tree.args.args[0].annotation.attr
if input_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[0],
'Message input type annotation not a supported message type')
self._input_message_var = tree.args.args[0].arg
self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')
self.write(', ')
if not tree.args.args[1].annotation:
self.RaiseError(tree.args.args[1],
'Message output requires a supported type annotation')
if not isinstance(tree.args.args[1].annotation, ast.Attribute):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[1].annotation.value, ast.Name):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
output_message_attr = tree.args.args[1
].annotation.value.id + '.' + tree.args.args[1].annotation.attr
if output_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[1],
'Message output type annotation not a supported message type')
self._output_message_var = tree.args.args[1].arg
self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')
def dispatchType(self, tree):
"""
There is a limited set of types and formats of type description supported. Types can be either;
1) A python built in type of int or float, or
2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16
This function translates and a catches unsupported types but does not translate a function call (i.e. cast)
"""
if isinstance(tree, ast.Name):
if tree.id not in self.basic_arg_types:
self.RaiseError(tree, 'Not a supported type')
self.write(tree.id)
elif isinstance(tree, ast.Attribute):
if not isinstance(tree.value, ast.Name):
self.RaiseError(tree, 'Not a supported type')
if not (tree.value.id == 'numpy' or tree.value.id == 'np'):
self.RaiseError(tree, 'Not a supported type')
if tree.attr not in self.numpytypes:
self.RaiseError(tree, 'Not a supported numpy type')
self.write(self.numpytypes[tree.attr])
else:
self.RaiseError(tree, 'Not a supported type')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def dispatchMessageLoop(self, tree):
"""
This is a special case of a range based for loop in which iterator item returns a const referecne to the message.
Any user specified message value can be used.
"""
self.fill('for (const auto& ')
self.dispatch(tree.target)
self.write(' : ')
if isinstance(tree.iter, ast.Name):
if not tree.iter.id == self._input_message_var:
self.RaiseError(t,
f"Message input loop requires use of '{self._input_message_var}' as iterator."
)
self.write(f'FLAMEGPU->{self._input_message_var}')
elif isinstance(tree.iter, ast.Call):
self.dispatchMessageIteratorCall(tree.iter)
else:
self.RaiseError(tree,
f'Message input loop iterator in unsupported format')
self.write(')')
self._message_iterator_var = tree.target.id
self.enter()
self.dispatch(tree.body)
self.leave()
self._message_iterator_var = None
def dispatchMemberFunction(self, t, t_parent):
"""
A very limited set of function calls to members are supported so these are fully evaluated here.
t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)
Function calls permitted are;
* pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.
* message_input.function - a call to the message input variable (the name of which is specified in the function definition)
* msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)
* message_output.function - a call to the message output variable (the name of which is specified in the function definition)
* pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.
* math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`
* numpy.type - Any numpy types are translated to static casts
"""
if not hasattr(t, 'value'):
self.RaiseError(t, f'Function call is in an unsupported format.')
if isinstance(t.value, ast.Attribute):
t_parent.call_type = None
if not isinstance(t.value.value, ast.Name):
self.RaiseError(t, 'Unknown or unsupported nested attribute')
if (t.value.value.id == 'pyflamegpu' and t.value.attr ==
'environment'):
self.write('FLAMEGPU->environment.')
if t.attr in self.fgpu_env_funcs:
self.write(t.attr)
elif t.attr.startswith('getProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getProperty'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment property function."
)
self.write(py_func)
t_parent.call_type = 'Environment'
elif t.attr.startswith('getMacroProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getMacroProperty'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function."
)
self.dispatchMacroEnvFunction(t, t_parent)
t_parent.call_type = 'MacroEnvironment'
else:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.environment object"
)
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':
self.write('FLAMEGPU->random.')
if t.attr in self.fgpu_rand_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'uniform', 'normal', 'logNormal'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.random object"
)
self.write(py_func)
t_parent.call_type = 'Random'
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':
self.write('FLAMEGPU->agent_out.')
if t.attr in self.fgpu_agent_out_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.agent_out object"
)
self.write(py_func)
t_parent.call_type = 'AgentOut'
else:
self.RaiseError(t,
f'Unknown or unsupported nested attribute in {t.value.value.id}'
)
elif isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
self.write('FLAMEGPU->')
if t.attr in self.fgpu_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable', 'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu object"
)
self.write(py_func)
elif t.value.id == self._input_message_var:
if t.attr in self.fgpu_input_msg_funcs:
self.write(f'FLAMEGPU->{self._input_message_var}.')
self.write(t.attr)
else:
self.RaiseError(t,
f"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'"
)
elif self._message_iterator_var and t.value.id == self._message_iterator_var:
self.write(f'{self._message_iterator_var}.')
if t.attr in self.fgpu_input_msg_iter_var_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object"
)
self.write(py_func)
elif t.value.id == self._output_message_var:
self.write('FLAMEGPU->message_out.')
if t.attr in self.fgpu_output_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object"
)
self.write(py_func)
elif t.value.id == 'math':
self.write(t.attr)
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(f'static_cast<{self.numpytypes[t.attr]}>')
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
elif t.value.id in self._locals:
self.write(f'{t.value.id}.{t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifier not supported")
elif isinstance(t.value, ast.Call):
self.dispatchMemberFunction(t.value.func, t.value)
if t.value.call_type != 'MacroEnvironment':
self.RaiseError(t, f'Function call {t.attr} is not supported')
if not t.attr in self.fgpu_env_macro_funcs:
self.RaiseError(t,
f'Function {t.attr} is not a valid macro environment function'
)
self.write('(')
self._CallArguments(t.value)
self.write(')')
self.write(f'.{t.attr}')
else:
self.RaiseError(t, 'Unsupported function call syntax')
def _Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Expression(self, tree):
self.dispatch(tree.body)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _ImportFrom(self, t):
self.RaiseError(t, 'Importing of modules not supported')
def _Assign(self, t):
"""
Assignment will use the auto type to define a variable at first use else will perform standard assignment.
Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.
Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.
"""
if len(t.targets) > 1:
self.RaiseError(t, 'Assignment to multiple targets not supported')
if not isinstance(t.targets[0], ast.Name):
self.RaiseError(t,
'Assignment to complex expressions not supported')
self.fill()
if t.targets[0].id not in self._locals:
self.write('auto ')
self._locals.append(t.targets[0].id)
self.dispatch(t.targets[0])
self.write(' = ')
self.dispatch(t.value)
self.write(';')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Continue(self, t):
self.fill('continue;')
<|reserved_special_token_0|>
def _Assert(self, t):
"""
cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy
"""
self.RaiseError(t, 'Assert not supported')
<|reserved_special_token_0|>
def _Print(self, t):
"""
This is old school python printing so no need to support
"""
self.RaiseError(t, 'Print not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Yield(self, t):
self.RaiseError(t, 'Yield not supported')
def _YieldFrom(self, t):
self.RaiseError(t, 'Yield from not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _TryExcept(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _TryFinally(self, t):
self.RaiseError(t, 'Exceptions not supported')
<|reserved_special_token_0|>
def _ClassDef(self, t):
self.RaiseError(t, 'Class definitions not supported')
<|reserved_special_token_0|>
def _AsyncFunctionDef(self, t):
self.RaiseError(t, 'Async functions not supported')
def _For(self, t):
"""
Two type for for loop are supported. Either;
1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'
2) A range based for loop with 1 to 3 arguments which is converted into a c style loop
"""
if isinstance(t.iter, ast.Name):
if t.iter.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
"Range based for loops only support message iteration using 'message_in' iterator"
)
elif t.orelse:
self.RaiseError(t, 'For else not supported')
elif isinstance(t.iter, ast.Call):
if isinstance(t.iter.func, ast.Name):
if t.iter.func.id == self._input_message_var:
self.dispatchMessageLoop(t)
elif t.iter.func.id == 'range':
if len(t.iter.args) == 1:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=0;')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 2:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 3:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('+=')
self.dispatch(t.iter.args[2])
self.write(')')
else:
self.RaiseError(t,
"Range based for loops requires use of 'range' function with arguments and not keywords"
)
self.enter()
self.dispatch(t.body)
self.leave()
else:
self.RaiseError(t,
"Range based for loops only support calls to the 'range' function"
)
elif isinstance(t.iter.func, ast.Attribute):
if t.iter.func.value.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
'Range based for loops only support calling members of message input variable'
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _While(self, t):
"""
Straightforward translation to c style while loop
"""
self.fill('while (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.RaiseError(t, 'While else not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Bytes(self, t):
self.RaiseError(t, 'Byte strings and Bytes function not supported')
<|reserved_special_token_0|>
def _JoinedStr(self, t):
self.RaiseError(t, 'Joined strings not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _NameConstant(self, t):
if t.value == None:
self.write(0)
elif t.value:
self.write('true')
else:
self.write('false')
def _Repr(self, t):
self.RaiseError(t, 'Repr not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _List(self, t):
self.RaiseError(t, 'Lists not supported')
<|reserved_special_token_0|>
def _GeneratorExp(self, t):
self.RaiseError(t, 'Generator expressions not supported')
def _SetComp(self, t):
self.RaiseError(t, 'Set comprehension not supported')
def _DictComp(self, t):
self.RaiseError(t, 'Dictionary comprehension not supported')
def _comprehension(self, t):
self.RaiseError(t, 'Comprehension not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Tuple(self, t):
self.RaiseError(t, 'Tuples not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _BinOp(self, t):
"""
Python style pow and floordiv are not supported so translate to a function call.
No matrix mul support.
"""
op_name = t.op.__class__.__name__
if op_name == 'Pow':
self.write('pow(')
self.dispatch(t.left)
self.write(', ')
self.dispatch(t.right)
self.write(')')
elif op_name == 'FloorDiv':
self.write('floor(')
self.dispatch(t.left)
self.write('/')
self.dispatch(t.right)
self.write(')')
elif op_name == 'MatMult':
self.RaiseError(t, 'Matrix multiplier operator not supported')
else:
self.write('(')
self.dispatch(t.left)
self.write(' ' + self.binop[op_name] + ' ')
self.dispatch(t.right)
self.write(')')
<|reserved_special_token_0|>
def _Compare(self, t):
self.dispatch(t.left)
for o, e in zip(t.ops, t.comparators):
if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':
self.RaiseError(t, 'In and NotIn operators not supported')
self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')
self.dispatch(e)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Attribute(self, t):
"""
A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.
Attributes supported are only;
* pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.
* math.constant - Any supported math constants are translated to C definition versions
"""
func_dict = None
if isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
if t.attr in self.fgpu_attrs:
self.write('flamegpu::')
self.write(t.attr)
else:
self.RaiseError(t,
f"Attribute '{t.attr}' does not exist in pyflamegpu object"
)
elif t.value.id == 'math':
if t.attr in self.mathconsts:
self.write(self.mathconsts[t.attr])
else:
self.RaiseError(t, f"Unsupported math constant '{t.attr}'")
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(self.numpytypes[t.attr])
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifiers not supported")
else:
self.RaiseError(t, 'Unsupported attribute')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Ellipsis(self, t):
self.RaiseError(t, 'Ellipsis values not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _arg(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, 'Arguments should already have been processed')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _alias(self, t):
self.RaiseError(t, 'Aliasing is not supported')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CodeGenerator:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, tree, file=sys.stdout):
"""CodeGenerator(tree, file=sys.stdout) -> None.
Print the source for tree to file."""
self.f = file
self.future_imports = []
self._indent = 0
self._locals = ['pyflamegpu']
self._device_functions = []
self._message_iterator_var = None
self._input_message_var = 'message_in'
self._output_message_var = 'message_out'
self.dispatch(tree)
print('', file=self.f)
self.f.flush()
<|reserved_special_token_0|>
def fill(self, text=''):
"""Indent a piece of text, according to the current indentation level"""
self.f.write('\n' + ' ' * self._indent + text)
<|reserved_special_token_0|>
def enter(self):
"""Print '{', and increase the indentation."""
self.write('{')
self._indent += 1
def leave(self):
"""Decrease the indentation level and Print '}'"""
self._indent -= 1
self.fill('}')
<|reserved_special_token_0|>
def RaiseWarning(self, tree, str):
warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')
def RaiseError(self, tree, str):
raise CodeGenException(
f'Error ({tree.lineno}, {tree.col_offset}): {str}')
<|reserved_special_token_0|>
def dispatchFGPUFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`
Type hinting is required to translate a type into a FLAME GPU Message type implementation
"""
self._locals = ['pyflamegpu']
if len(tree.args.args) != 2:
self.RaiseError(tree,
'Expected two FLAME GPU function arguments (input message and output message)'
)
if not tree.args.args[0].annotation:
self.RaiseError(tree.args.args[0],
'Message input requires a supported type annotation')
if not isinstance(tree.args.args[0].annotation, ast.Attribute):
self.RaiseError(tree.args.args[0],
'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[0].annotation.value, ast.Name):
self.RaiseError(tree.args.args[0],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
input_message_attr = tree.args.args[0
].annotation.value.id + '.' + tree.args.args[0].annotation.attr
if input_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[0],
'Message input type annotation not a supported message type')
self._input_message_var = tree.args.args[0].arg
self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')
self.write(', ')
if not tree.args.args[1].annotation:
self.RaiseError(tree.args.args[1],
'Message output requires a supported type annotation')
if not isinstance(tree.args.args[1].annotation, ast.Attribute):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[1].annotation.value, ast.Name):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
output_message_attr = tree.args.args[1
].annotation.value.id + '.' + tree.args.args[1].annotation.attr
if output_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[1],
'Message output type annotation not a supported message type')
self._output_message_var = tree.args.args[1].arg
self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')
def dispatchType(self, tree):
"""
There is a limited set of types and formats of type description supported. Types can be either;
1) A python built in type of int or float, or
2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16
This function translates and a catches unsupported types but does not translate a function call (i.e. cast)
"""
if isinstance(tree, ast.Name):
if tree.id not in self.basic_arg_types:
self.RaiseError(tree, 'Not a supported type')
self.write(tree.id)
elif isinstance(tree, ast.Attribute):
if not isinstance(tree.value, ast.Name):
self.RaiseError(tree, 'Not a supported type')
if not (tree.value.id == 'numpy' or tree.value.id == 'np'):
self.RaiseError(tree, 'Not a supported type')
if tree.attr not in self.numpytypes:
self.RaiseError(tree, 'Not a supported numpy type')
self.write(self.numpytypes[tree.attr])
else:
self.RaiseError(tree, 'Not a supported type')
<|reserved_special_token_0|>
def dispatchMessageIteratorCall(self, tree):
"""
Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())
Using this function avoid using the global call one which may accept member function calls to things that are not iterators.
"""
if isinstance(tree.func, ast.Name):
self.write(f'FLAMEGPU->{tree.func.id}')
if isinstance(tree.func, ast.Attribute):
if isinstance(tree.func.value, ast.Name):
if not tree.func.attr in self.fgpu_input_msg_iter_funcs:
self.RaiseError(tree,
f"Message input loop iterator '{tree.func.attr}' is not supported."
)
self.write(f'FLAMEGPU->{tree.func.value.id}.{tree.func.attr}')
else:
self.RaiseError(tree,
'Message input loop iterator format incorrect.')
self.write('(')
self._CallArguments(tree)
self.write(')')
def dispatchMessageLoop(self, tree):
"""
This is a special case of a range based for loop in which iterator item returns a const referecne to the message.
Any user specified message value can be used.
"""
self.fill('for (const auto& ')
self.dispatch(tree.target)
self.write(' : ')
if isinstance(tree.iter, ast.Name):
if not tree.iter.id == self._input_message_var:
self.RaiseError(t,
f"Message input loop requires use of '{self._input_message_var}' as iterator."
)
self.write(f'FLAMEGPU->{self._input_message_var}')
elif isinstance(tree.iter, ast.Call):
self.dispatchMessageIteratorCall(tree.iter)
else:
self.RaiseError(tree,
f'Message input loop iterator in unsupported format')
self.write(')')
self._message_iterator_var = tree.target.id
self.enter()
self.dispatch(tree.body)
self.leave()
self._message_iterator_var = None
def dispatchMemberFunction(self, t, t_parent):
"""
A very limited set of function calls to members are supported so these are fully evaluated here.
t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)
Function calls permitted are;
* pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.
* message_input.function - a call to the message input variable (the name of which is specified in the function definition)
* msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)
* message_output.function - a call to the message output variable (the name of which is specified in the function definition)
* pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.
* math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`
* numpy.type - Any numpy types are translated to static casts
"""
if not hasattr(t, 'value'):
self.RaiseError(t, f'Function call is in an unsupported format.')
if isinstance(t.value, ast.Attribute):
t_parent.call_type = None
if not isinstance(t.value.value, ast.Name):
self.RaiseError(t, 'Unknown or unsupported nested attribute')
if (t.value.value.id == 'pyflamegpu' and t.value.attr ==
'environment'):
self.write('FLAMEGPU->environment.')
if t.attr in self.fgpu_env_funcs:
self.write(t.attr)
elif t.attr.startswith('getProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getProperty'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment property function."
)
self.write(py_func)
t_parent.call_type = 'Environment'
elif t.attr.startswith('getMacroProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getMacroProperty'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function."
)
self.dispatchMacroEnvFunction(t, t_parent)
t_parent.call_type = 'MacroEnvironment'
else:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.environment object"
)
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':
self.write('FLAMEGPU->random.')
if t.attr in self.fgpu_rand_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'uniform', 'normal', 'logNormal'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.random object"
)
self.write(py_func)
t_parent.call_type = 'Random'
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':
self.write('FLAMEGPU->agent_out.')
if t.attr in self.fgpu_agent_out_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.agent_out object"
)
self.write(py_func)
t_parent.call_type = 'AgentOut'
else:
self.RaiseError(t,
f'Unknown or unsupported nested attribute in {t.value.value.id}'
)
elif isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
self.write('FLAMEGPU->')
if t.attr in self.fgpu_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable', 'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu object"
)
self.write(py_func)
elif t.value.id == self._input_message_var:
if t.attr in self.fgpu_input_msg_funcs:
self.write(f'FLAMEGPU->{self._input_message_var}.')
self.write(t.attr)
else:
self.RaiseError(t,
f"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'"
)
elif self._message_iterator_var and t.value.id == self._message_iterator_var:
self.write(f'{self._message_iterator_var}.')
if t.attr in self.fgpu_input_msg_iter_var_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object"
)
self.write(py_func)
elif t.value.id == self._output_message_var:
self.write('FLAMEGPU->message_out.')
if t.attr in self.fgpu_output_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object"
)
self.write(py_func)
elif t.value.id == 'math':
self.write(t.attr)
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(f'static_cast<{self.numpytypes[t.attr]}>')
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
elif t.value.id in self._locals:
self.write(f'{t.value.id}.{t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifier not supported")
elif isinstance(t.value, ast.Call):
self.dispatchMemberFunction(t.value.func, t.value)
if t.value.call_type != 'MacroEnvironment':
self.RaiseError(t, f'Function call {t.attr} is not supported')
if not t.attr in self.fgpu_env_macro_funcs:
self.RaiseError(t,
f'Function {t.attr} is not a valid macro environment function'
)
self.write('(')
self._CallArguments(t.value)
self.write(')')
self.write(f'.{t.attr}')
else:
self.RaiseError(t, 'Unsupported function call syntax')
def _Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Expression(self, tree):
self.dispatch(tree.body)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _ImportFrom(self, t):
self.RaiseError(t, 'Importing of modules not supported')
def _Assign(self, t):
"""
Assignment will use the auto type to define a variable at first use else will perform standard assignment.
Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.
Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.
"""
if len(t.targets) > 1:
self.RaiseError(t, 'Assignment to multiple targets not supported')
if not isinstance(t.targets[0], ast.Name):
self.RaiseError(t,
'Assignment to complex expressions not supported')
self.fill()
if t.targets[0].id not in self._locals:
self.write('auto ')
self._locals.append(t.targets[0].id)
self.dispatch(t.targets[0])
self.write(' = ')
self.dispatch(t.value)
self.write(';')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Continue(self, t):
self.fill('continue;')
<|reserved_special_token_0|>
def _Assert(self, t):
"""
cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy
"""
self.RaiseError(t, 'Assert not supported')
<|reserved_special_token_0|>
def _Print(self, t):
"""
This is old school python printing so no need to support
"""
self.RaiseError(t, 'Print not supported')
<|reserved_special_token_0|>
def _Nonlocal(self, t):
self.RaiseError(t, "Use of 'nonlocal' not supported")
<|reserved_special_token_0|>
def _Yield(self, t):
self.RaiseError(t, 'Yield not supported')
def _YieldFrom(self, t):
self.RaiseError(t, 'Yield from not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _TryExcept(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _TryFinally(self, t):
self.RaiseError(t, 'Exceptions not supported')
<|reserved_special_token_0|>
def _ClassDef(self, t):
self.RaiseError(t, 'Class definitions not supported')
<|reserved_special_token_0|>
def _AsyncFunctionDef(self, t):
self.RaiseError(t, 'Async functions not supported')
def _For(self, t):
"""
Two type for for loop are supported. Either;
1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'
2) A range based for loop with 1 to 3 arguments which is converted into a c style loop
"""
if isinstance(t.iter, ast.Name):
if t.iter.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
"Range based for loops only support message iteration using 'message_in' iterator"
)
elif t.orelse:
self.RaiseError(t, 'For else not supported')
elif isinstance(t.iter, ast.Call):
if isinstance(t.iter.func, ast.Name):
if t.iter.func.id == self._input_message_var:
self.dispatchMessageLoop(t)
elif t.iter.func.id == 'range':
if len(t.iter.args) == 1:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=0;')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 2:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 3:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('+=')
self.dispatch(t.iter.args[2])
self.write(')')
else:
self.RaiseError(t,
"Range based for loops requires use of 'range' function with arguments and not keywords"
)
self.enter()
self.dispatch(t.body)
self.leave()
else:
self.RaiseError(t,
"Range based for loops only support calls to the 'range' function"
)
elif isinstance(t.iter.func, ast.Attribute):
if t.iter.func.value.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
'Range based for loops only support calling members of message input variable'
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _While(self, t):
"""
Straightforward translation to c style while loop
"""
self.fill('while (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.RaiseError(t, 'While else not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Bytes(self, t):
self.RaiseError(t, 'Byte strings and Bytes function not supported')
<|reserved_special_token_0|>
def _JoinedStr(self, t):
self.RaiseError(t, 'Joined strings not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _NameConstant(self, t):
if t.value == None:
self.write(0)
elif t.value:
self.write('true')
else:
self.write('false')
def _Repr(self, t):
self.RaiseError(t, 'Repr not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _List(self, t):
self.RaiseError(t, 'Lists not supported')
<|reserved_special_token_0|>
def _GeneratorExp(self, t):
self.RaiseError(t, 'Generator expressions not supported')
def _SetComp(self, t):
self.RaiseError(t, 'Set comprehension not supported')
def _DictComp(self, t):
self.RaiseError(t, 'Dictionary comprehension not supported')
def _comprehension(self, t):
self.RaiseError(t, 'Comprehension not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Tuple(self, t):
self.RaiseError(t, 'Tuples not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _BinOp(self, t):
"""
Python style pow and floordiv are not supported so translate to a function call.
No matrix mul support.
"""
op_name = t.op.__class__.__name__
if op_name == 'Pow':
self.write('pow(')
self.dispatch(t.left)
self.write(', ')
self.dispatch(t.right)
self.write(')')
elif op_name == 'FloorDiv':
self.write('floor(')
self.dispatch(t.left)
self.write('/')
self.dispatch(t.right)
self.write(')')
elif op_name == 'MatMult':
self.RaiseError(t, 'Matrix multiplier operator not supported')
else:
self.write('(')
self.dispatch(t.left)
self.write(' ' + self.binop[op_name] + ' ')
self.dispatch(t.right)
self.write(')')
<|reserved_special_token_0|>
def _Compare(self, t):
self.dispatch(t.left)
for o, e in zip(t.ops, t.comparators):
if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':
self.RaiseError(t, 'In and NotIn operators not supported')
self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')
self.dispatch(e)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Attribute(self, t):
"""
A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.
Attributes supported are only;
* pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.
* math.constant - Any supported math constants are translated to C definition versions
"""
func_dict = None
if isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
if t.attr in self.fgpu_attrs:
self.write('flamegpu::')
self.write(t.attr)
else:
self.RaiseError(t,
f"Attribute '{t.attr}' does not exist in pyflamegpu object"
)
elif t.value.id == 'math':
if t.attr in self.mathconsts:
self.write(self.mathconsts[t.attr])
else:
self.RaiseError(t, f"Unsupported math constant '{t.attr}'")
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(self.numpytypes[t.attr])
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifiers not supported")
else:
self.RaiseError(t, 'Unsupported attribute')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Ellipsis(self, t):
self.RaiseError(t, 'Ellipsis values not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _arg(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, 'Arguments should already have been processed')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _alias(self, t):
self.RaiseError(t, 'Aliasing is not supported')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CodeGenerator:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, tree, file=sys.stdout):
"""CodeGenerator(tree, file=sys.stdout) -> None.
Print the source for tree to file."""
self.f = file
self.future_imports = []
self._indent = 0
self._locals = ['pyflamegpu']
self._device_functions = []
self._message_iterator_var = None
self._input_message_var = 'message_in'
self._output_message_var = 'message_out'
self.dispatch(tree)
print('', file=self.f)
self.f.flush()
<|reserved_special_token_0|>
def fill(self, text=''):
"""Indent a piece of text, according to the current indentation level"""
self.f.write('\n' + ' ' * self._indent + text)
def write(self, text):
"""Append a piece of text to the current line."""
self.f.write(str(text))
def enter(self):
"""Print '{', and increase the indentation."""
self.write('{')
self._indent += 1
def leave(self):
"""Decrease the indentation level and Print '}'"""
self._indent -= 1
self.fill('}')
<|reserved_special_token_0|>
def RaiseWarning(self, tree, str):
warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')
def RaiseError(self, tree, str):
raise CodeGenException(
f'Error ({tree.lineno}, {tree.col_offset}): {str}')
def dispatchMacroEnvFunction(self, tree, tree_parent):
"""
Function will handle a getMacroEnvironment function (assuming it is correctly formatted (by checking with _deviceVariableFunctionName first))
"""
cpp_func_name = 'getMacroProperty'
py_func = tree.attr
py_type = py_func[len(cpp_func_name):]
if py_type not in self._fgpu_types:
self.RaiseError(tree, f"'{py_type}' is not a valid FLAME GPU type")
t = self._fgpu_types[py_type]
cpp_func_name += f'<{t}'
if not tree_parent.args:
self.RaiseError(tree,
f" Macro environment function '{py_func}' is expected to have some arguments."
)
if len(tree_parent.args) > 1:
bounds = tree_parent.args[1:]
for i in bounds:
if isinstance(i, ast.Num):
if not isinstance(i.n, int):
self.RaiseError(tree,
f" Macro environment function argument '{i}' should be an integer value."
)
cpp_func_name += f', {i.n}'
else:
if not isinstance(i, ast.Constant):
self.RaiseError(tree,
f" Macro environment function argument '{i}' should be an constant value (or Num in Python <3.8)."
)
if not isinstance(i.value, int):
self.RaiseError(tree,
f" Macro environment function argument '{i}' should be an integer value."
)
cpp_func_name += f', {i.value}'
del tree_parent.args[1:]
cpp_func_name += '>'
self.write(cpp_func_name)
def dispatchFGPUFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`
Type hinting is required to translate a type into a FLAME GPU Message type implementation
"""
self._locals = ['pyflamegpu']
if len(tree.args.args) != 2:
self.RaiseError(tree,
'Expected two FLAME GPU function arguments (input message and output message)'
)
if not tree.args.args[0].annotation:
self.RaiseError(tree.args.args[0],
'Message input requires a supported type annotation')
if not isinstance(tree.args.args[0].annotation, ast.Attribute):
self.RaiseError(tree.args.args[0],
'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[0].annotation.value, ast.Name):
self.RaiseError(tree.args.args[0],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
input_message_attr = tree.args.args[0
].annotation.value.id + '.' + tree.args.args[0].annotation.attr
if input_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[0],
'Message input type annotation not a supported message type')
self._input_message_var = tree.args.args[0].arg
self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')
self.write(', ')
if not tree.args.args[1].annotation:
self.RaiseError(tree.args.args[1],
'Message output requires a supported type annotation')
if not isinstance(tree.args.args[1].annotation, ast.Attribute):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[1].annotation.value, ast.Name):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
output_message_attr = tree.args.args[1
].annotation.value.id + '.' + tree.args.args[1].annotation.attr
if output_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[1],
'Message output type annotation not a supported message type')
self._output_message_var = tree.args.args[1].arg
self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')
def dispatchType(self, tree):
"""
There is a limited set of types and formats of type description supported. Types can be either;
1) A python built in type of int or float, or
2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16
This function translates and a catches unsupported types but does not translate a function call (i.e. cast)
"""
if isinstance(tree, ast.Name):
if tree.id not in self.basic_arg_types:
self.RaiseError(tree, 'Not a supported type')
self.write(tree.id)
elif isinstance(tree, ast.Attribute):
if not isinstance(tree.value, ast.Name):
self.RaiseError(tree, 'Not a supported type')
if not (tree.value.id == 'numpy' or tree.value.id == 'np'):
self.RaiseError(tree, 'Not a supported type')
if tree.attr not in self.numpytypes:
self.RaiseError(tree, 'Not a supported numpy type')
self.write(self.numpytypes[tree.attr])
else:
self.RaiseError(tree, 'Not a supported type')
def dispatchFGPUDeviceFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU device function. Arguments must use type hinting to be translated to cpp.
"""
self._locals = ['pyflamegpu']
first = True
annotation = None
for arg in tree.args.args:
if not arg.annotation:
self.RaiseError(arg,
'Device function argument requires type annotation')
if not first:
self.write(', ')
self.dispatchType(arg.annotation)
self.write(f' {arg.arg}')
self._locals.append(arg.arg)
first = False
def dispatchMessageIteratorCall(self, tree):
"""
Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())
Using this function avoid using the global call one which may accept member function calls to things that are not iterators.
"""
if isinstance(tree.func, ast.Name):
self.write(f'FLAMEGPU->{tree.func.id}')
if isinstance(tree.func, ast.Attribute):
if isinstance(tree.func.value, ast.Name):
if not tree.func.attr in self.fgpu_input_msg_iter_funcs:
self.RaiseError(tree,
f"Message input loop iterator '{tree.func.attr}' is not supported."
)
self.write(f'FLAMEGPU->{tree.func.value.id}.{tree.func.attr}')
else:
self.RaiseError(tree,
'Message input loop iterator format incorrect.')
self.write('(')
self._CallArguments(tree)
self.write(')')
def dispatchMessageLoop(self, tree):
"""
This is a special case of a range based for loop in which iterator item returns a const referecne to the message.
Any user specified message value can be used.
"""
self.fill('for (const auto& ')
self.dispatch(tree.target)
self.write(' : ')
if isinstance(tree.iter, ast.Name):
if not tree.iter.id == self._input_message_var:
self.RaiseError(t,
f"Message input loop requires use of '{self._input_message_var}' as iterator."
)
self.write(f'FLAMEGPU->{self._input_message_var}')
elif isinstance(tree.iter, ast.Call):
self.dispatchMessageIteratorCall(tree.iter)
else:
self.RaiseError(tree,
f'Message input loop iterator in unsupported format')
self.write(')')
self._message_iterator_var = tree.target.id
self.enter()
self.dispatch(tree.body)
self.leave()
self._message_iterator_var = None
def dispatchMemberFunction(self, t, t_parent):
"""
A very limited set of function calls to members are supported so these are fully evaluated here.
t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)
Function calls permitted are;
* pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.
* message_input.function - a call to the message input variable (the name of which is specified in the function definition)
* msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)
* message_output.function - a call to the message output variable (the name of which is specified in the function definition)
* pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.
* math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`
* numpy.type - Any numpy types are translated to static casts
"""
if not hasattr(t, 'value'):
self.RaiseError(t, f'Function call is in an unsupported format.')
if isinstance(t.value, ast.Attribute):
t_parent.call_type = None
if not isinstance(t.value.value, ast.Name):
self.RaiseError(t, 'Unknown or unsupported nested attribute')
if (t.value.value.id == 'pyflamegpu' and t.value.attr ==
'environment'):
self.write('FLAMEGPU->environment.')
if t.attr in self.fgpu_env_funcs:
self.write(t.attr)
elif t.attr.startswith('getProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getProperty'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment property function."
)
self.write(py_func)
t_parent.call_type = 'Environment'
elif t.attr.startswith('getMacroProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getMacroProperty'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function."
)
self.dispatchMacroEnvFunction(t, t_parent)
t_parent.call_type = 'MacroEnvironment'
else:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.environment object"
)
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':
self.write('FLAMEGPU->random.')
if t.attr in self.fgpu_rand_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'uniform', 'normal', 'logNormal'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.random object"
)
self.write(py_func)
t_parent.call_type = 'Random'
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':
self.write('FLAMEGPU->agent_out.')
if t.attr in self.fgpu_agent_out_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.agent_out object"
)
self.write(py_func)
t_parent.call_type = 'AgentOut'
else:
self.RaiseError(t,
f'Unknown or unsupported nested attribute in {t.value.value.id}'
)
elif isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
self.write('FLAMEGPU->')
if t.attr in self.fgpu_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable', 'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu object"
)
self.write(py_func)
elif t.value.id == self._input_message_var:
if t.attr in self.fgpu_input_msg_funcs:
self.write(f'FLAMEGPU->{self._input_message_var}.')
self.write(t.attr)
else:
self.RaiseError(t,
f"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'"
)
elif self._message_iterator_var and t.value.id == self._message_iterator_var:
self.write(f'{self._message_iterator_var}.')
if t.attr in self.fgpu_input_msg_iter_var_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object"
)
self.write(py_func)
elif t.value.id == self._output_message_var:
self.write('FLAMEGPU->message_out.')
if t.attr in self.fgpu_output_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object"
)
self.write(py_func)
elif t.value.id == 'math':
self.write(t.attr)
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(f'static_cast<{self.numpytypes[t.attr]}>')
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
elif t.value.id in self._locals:
self.write(f'{t.value.id}.{t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifier not supported")
elif isinstance(t.value, ast.Call):
self.dispatchMemberFunction(t.value.func, t.value)
if t.value.call_type != 'MacroEnvironment':
self.RaiseError(t, f'Function call {t.attr} is not supported')
if not t.attr in self.fgpu_env_macro_funcs:
self.RaiseError(t,
f'Function {t.attr} is not a valid macro environment function'
)
self.write('(')
self._CallArguments(t.value)
self.write(')')
self.write(f'.{t.attr}')
else:
self.RaiseError(t, 'Unsupported function call syntax')
def _Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Expression(self, tree):
self.dispatch(tree.body)
def _Expr(self, tree):
"""
Same as a standard python expression but ends with semicolon
"""
if isinstance(tree.value, ast.Constant):
if isinstance(tree.value.value, str):
return
elif isinstance(tree.value, ast.Str):
return
self.fill()
self.dispatch(tree.value)
self.write(';')
def _NamedExpr(self, tree):
"""
No such concept in C++. Standard assignment can be used in any location.
"""
self.write('(')
self.dispatch(tree.target)
self.write(' = ')
self.dispatch(tree.value)
self.write(')')
def _Import(self, t):
self.RaiseError(t, 'Importing of modules not supported')
def _ImportFrom(self, t):
self.RaiseError(t, 'Importing of modules not supported')
def _Assign(self, t):
"""
Assignment will use the auto type to define a variable at first use else will perform standard assignment.
Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.
Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.
"""
if len(t.targets) > 1:
self.RaiseError(t, 'Assignment to multiple targets not supported')
if not isinstance(t.targets[0], ast.Name):
self.RaiseError(t,
'Assignment to complex expressions not supported')
self.fill()
if t.targets[0].id not in self._locals:
self.write('auto ')
self._locals.append(t.targets[0].id)
self.dispatch(t.targets[0])
self.write(' = ')
self.dispatch(t.value)
self.write(';')
def _AugAssign(self, t):
"""
Similar to assignment in terms of restrictions. E.g. Allow only single named variable assignments.
Also requires the named variable to already exist in scope.
"""
if not isinstance(t.target, ast.Name):
self.RaiseError(t,
'Augmented assignment to complex expressions not supported')
if t.target.id not in self._locals:
self.RaiseError(t,
'Augmented assignment not permitted on variables not already assigned previously'
)
self.fill()
self.dispatch(t.target)
self.write(' ' + self.binop[t.op.__class__.__name__] + '= ')
self.dispatch(t.value)
self.write(';')
def _AnnAssign(self, t):
if not isinstance(t.target, ast.Name):
self.RaiseError(t,
'Augmented assignment to complex expressions not supported')
self.fill()
self.dispatchType(t.annotation)
self.write(' ')
self.dispatch(t.target)
if t.value:
self.write(' = ')
self.dispatch(t.value)
self.write(';')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Break(self, t):
self.fill('break;')
def _Continue(self, t):
self.fill('continue;')
def _Delete(self, t):
self.RaiseError(t, 'Deletion not supported')
def _Assert(self, t):
"""
cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy
"""
self.RaiseError(t, 'Assert not supported')
def _Exec(self, t):
self.RaiseError(t, 'Exec not supported')
def _Print(self, t):
"""
This is old school python printing so no need to support
"""
self.RaiseError(t, 'Print not supported')
def _Global(self, t):
self.RaiseError(t, "Use of 'global' not supported")
def _Nonlocal(self, t):
self.RaiseError(t, "Use of 'nonlocal' not supported")
<|reserved_special_token_0|>
def _Yield(self, t):
self.RaiseError(t, 'Yield not supported')
def _YieldFrom(self, t):
self.RaiseError(t, 'Yield from not supported')
def _Raise(self, t):
"""
Exceptions are obviously supported in cpp but not in CUDA device code
"""
self.RaiseError(t, 'Exception raising not supported')
def _Try(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _TryExcept(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _TryFinally(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _ExceptHandler(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _ClassDef(self, t):
self.RaiseError(t, 'Class definitions not supported')
def _FunctionDef(self, t):
"""
Checks the decorators of the function definition much must be either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'.
Each is then processed in a different way using a specific dispatcher.
Function calls are actually checked and only permitted (or user defined) function calls are supported.
"""
self.write('\n')
if len(t.decorator_list) != 1 or not isinstance(t.decorator_list[0],
ast.Attribute):
self.RaiseError(t,
"Function definitions require a single pyflamegpu decorator of either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'"
)
if t.decorator_list[0].attr == 'agent_function' and t.decorator_list[0
].value.id == 'pyflamegpu':
if getattr(t, 'returns', False):
self.RaiseWarning(t,
"Function definition return type not supported on 'pyflamegpu.agent_function'"
)
self.fill(f'FLAMEGPU_AGENT_FUNCTION({t.name}, ')
self.dispatchFGPUFunctionArgs(t)
self.write(')')
elif t.decorator_list[0
].attr == 'device_function' and t.decorator_list[0
].value.id == 'pyflamegpu':
self.fill(f'FLAMEGPU_DEVICE_FUNCTION ')
if t.returns:
self.dispatchType(t.returns)
else:
self.write('void')
self.write(f' {t.name}(')
self.dispatchFGPUDeviceFunctionArgs(t)
self.write(')')
self._device_functions.append(t.name)
elif t.decorator_list[0
].attr == 'agent_function_condition' and t.decorator_list[0
].value.id == 'pyflamegpu':
if not hasattr(t, 'returns'):
self.RaiseError(t,
"Agent function conditions must have a 'bool' return type specified as a return type annotation"
)
if not isinstance(t.returns, ast.Name):
self.RaiseError(t,
"Agent function conditions return type must be 'bool'")
if t.returns.id is not 'bool':
self.RaiseError(t,
"Agent function conditions return type must be 'bool'")
if t.args.args:
self.RaiseWarning(t,
'Agent function conditions does not support arguments. These will be discarded.'
)
self.fill(f'FLAMEGPU_AGENT_FUNCTION_CONDITION({t.name})')
else:
self.RaiseError(t,
"Function definition uses an unsupported decorator. Must use either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'"
)
self.enter()
self.dispatch(t.body)
self.leave()
def _AsyncFunctionDef(self, t):
self.RaiseError(t, 'Async functions not supported')
def _For(self, t):
"""
Two type for for loop are supported. Either;
1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'
2) A range based for loop with 1 to 3 arguments which is converted into a c style loop
"""
if isinstance(t.iter, ast.Name):
if t.iter.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
"Range based for loops only support message iteration using 'message_in' iterator"
)
elif t.orelse:
self.RaiseError(t, 'For else not supported')
elif isinstance(t.iter, ast.Call):
if isinstance(t.iter.func, ast.Name):
if t.iter.func.id == self._input_message_var:
self.dispatchMessageLoop(t)
elif t.iter.func.id == 'range':
if len(t.iter.args) == 1:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=0;')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 2:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 3:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('+=')
self.dispatch(t.iter.args[2])
self.write(')')
else:
self.RaiseError(t,
"Range based for loops requires use of 'range' function with arguments and not keywords"
)
self.enter()
self.dispatch(t.body)
self.leave()
else:
self.RaiseError(t,
"Range based for loops only support calls to the 'range' function"
)
elif isinstance(t.iter.func, ast.Attribute):
if t.iter.func.value.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
'Range based for loops only support calling members of message input variable'
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
def _AsyncFor(self, t):
self.RaiseError(t, 'Async for not supported')
def _If(self, t):
"""
Fairly straightforward translation to if, else if, else format
"""
self.fill('if (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0],
ast.If):
t = t.orelse[0]
self.fill('else if (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.fill('else')
self.enter()
self.dispatch(t.orelse)
self.leave()
def _While(self, t):
"""
Straightforward translation to c style while loop
"""
self.fill('while (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.RaiseError(t, 'While else not supported')
def _With(self, t):
self.RaiseError(t, 'With not supported')
def _AsyncWith(self, t):
self.RaiseError(t, 'Async with not supported')
def _Bytes(self, t):
self.RaiseError(t, 'Byte strings and Bytes function not supported')
<|reserved_special_token_0|>
def _JoinedStr(self, t):
self.RaiseError(t, 'Joined strings not supported')
<|reserved_special_token_0|>
def _fstring_JoinedStr(self, t, write):
self.RaiseError(t, 'F strings not supported')
<|reserved_special_token_0|>
def _fstring_Constant(self, t, write):
self.RaiseError(t, 'F strings not supported')
def _fstring_FormattedValue(self, t, write):
self.RaiseError(t, 'F strings not supported')
def _Name(self, t):
"""
Everything ends up as a Name once it is an identifier
"""
self.write(t.id)
def _NameConstant(self, t):
if t.value == None:
self.write(0)
elif t.value:
self.write('true')
else:
self.write('false')
def _Repr(self, t):
self.RaiseError(t, 'Repr not supported')
def _Constant(self, t):
"""
Restrict most types of constant except for numeric types and constant strings
Picks up some obvious conversions such as None and Bools
"""
value = t.value
if isinstance(value, tuple):
self.RaiseError(t, 'Tuples not supported')
if isinstance(value, dict):
self.RaiseError(t, 'Dictionaries not supported')
if isinstance(value, list):
self.RaiseError(t, 'Lists not supported')
elif value is Ellipsis:
self.RaiseError(t, 'Ellipsis not supported')
elif isinstance(value, str):
self.write(f'"{value}"')
elif isinstance(value, (bytes, bytearray)):
self.RaiseError(t, 'Byte strings and Bytes function not supported')
elif isinstance(value, bool):
if value:
self.write('true')
else:
self.write('false')
elif value == None:
self.write(0)
else:
self.write(repr(value))
def _Num(self, t):
self.write(repr(t.n))
def _List(self, t):
self.RaiseError(t, 'Lists not supported')
def _ListComp(self, t):
self.RaiseError(t, 'List comprehension not supported')
def _GeneratorExp(self, t):
self.RaiseError(t, 'Generator expressions not supported')
def _SetComp(self, t):
self.RaiseError(t, 'Set comprehension not supported')
def _DictComp(self, t):
self.RaiseError(t, 'Dictionary comprehension not supported')
def _comprehension(self, t):
self.RaiseError(t, 'Comprehension not supported')
def _IfExp(self, t):
"""
Equivalent to a ternary operator
"""
self.dispatch(t.test)
self.write(' ? ')
self.dispatch(t.body)
self.write(' : ')
self.dispatch(t.orelse)
<|reserved_special_token_0|>
def _Dict(self, t):
self.RaiseError(t, 'Dictionaries not supported')
def _Tuple(self, t):
self.RaiseError(t, 'Tuples not supported')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _BinOp(self, t):
"""
Python style pow and floordiv are not supported so translate to a function call.
No matrix mul support.
"""
op_name = t.op.__class__.__name__
if op_name == 'Pow':
self.write('pow(')
self.dispatch(t.left)
self.write(', ')
self.dispatch(t.right)
self.write(')')
elif op_name == 'FloorDiv':
self.write('floor(')
self.dispatch(t.left)
self.write('/')
self.dispatch(t.right)
self.write(')')
elif op_name == 'MatMult':
self.RaiseError(t, 'Matrix multiplier operator not supported')
else:
self.write('(')
self.dispatch(t.left)
self.write(' ' + self.binop[op_name] + ' ')
self.dispatch(t.right)
self.write(')')
<|reserved_special_token_0|>
def _Compare(self, t):
self.dispatch(t.left)
for o, e in zip(t.ops, t.comparators):
if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':
self.RaiseError(t, 'In and NotIn operators not supported')
self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')
self.dispatch(e)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Attribute(self, t):
"""
A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.
Attributes supported are only;
* pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.
* math.constant - Any supported math constants are translated to C definition versions
"""
func_dict = None
if isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
if t.attr in self.fgpu_attrs:
self.write('flamegpu::')
self.write(t.attr)
else:
self.RaiseError(t,
f"Attribute '{t.attr}' does not exist in pyflamegpu object"
)
elif t.value.id == 'math':
if t.attr in self.mathconsts:
self.write(self.mathconsts[t.attr])
else:
self.RaiseError(t, f"Unsupported math constant '{t.attr}'")
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(self.numpytypes[t.attr])
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifiers not supported")
else:
self.RaiseError(t, 'Unsupported attribute')
def _CallArguments(self, t):
comma = False
for e in t.args:
if comma:
self.write(', ')
else:
comma = True
self.dispatch(e)
if len(t.keywords):
self.RaiseWarning(t, 'Keyword argument not supported. Ignored.')
if sys.version_info[:2] < (3, 5):
if t.starargs:
self.RaiseWarning(t, 'Starargs not supported. Ignored.')
if t.kwargs:
self.RaiseWarning(t, 'Kwargs not supported. Ignored.')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _Starred(self, t):
self.RaiseError(t, 'Starred values not supported')
def _Ellipsis(self, t):
self.RaiseError(t, 'Ellipsis values not supported')
def _Index(self, t):
self.RaiseError(t, 'Index values not supported')
def _Slice(self, t):
self.RaiseError(t, 'Slicing values not supported')
<|reserved_special_token_0|>
def _arg(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, 'Arguments should already have been processed')
def _arguments(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, 'Arguments should already have been processed')
def _keyword(self, t):
self.RaiseError(t, 'Keywords are not supported')
def _Lambda(self, t):
self.RaiseError(t, 'Lambda is not supported')
def _alias(self, t):
self.RaiseError(t, 'Aliasing is not supported')
def _withitem(self, t):
self.RaiseError(t, 'With not supported')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class CodeGenerator:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def __init__(self, tree, file=sys.stdout):
"""CodeGenerator(tree, file=sys.stdout) -> None.
Print the source for tree to file."""
self.f = file
self.future_imports = []
self._indent = 0
self._locals = ['pyflamegpu']
self._device_functions = []
self._message_iterator_var = None
self._input_message_var = 'message_in'
self._output_message_var = 'message_out'
self.dispatch(tree)
print('', file=self.f)
self.f.flush()
def _deviceVariableFunctionName(self, tree, permitted_prefixes,
allow_lengths=True):
"""
Gets the device function name by translating a typed Python version to a templated cpp version.
Python functions looks like getVariableFloatArray6 and translate to getVariable<float, 6>
This function will detect and test against a set of known types and also extract the Array length
This function returns None if the string is invalid in format but only throws an error if the format is correct but the type is invalid.
"""
cpp_func_name = ''
py_func = tree.attr
for prefix in permitted_prefixes:
if py_func.startswith(prefix):
cpp_func_name = prefix
py_func = py_func[len(prefix):]
break
else:
return None
if allow_lengths:
type_and_length = py_func.split('Array')
if type_and_length[0] not in self._fgpu_types:
self.RaiseError(tree,
f"'{type_and_length[0]}' is not a valid FLAME GPU type")
t = self._fgpu_types[type_and_length[0]]
if len(type_and_length) == 1:
cpp_func_name += f'<{t}>'
elif len(type_and_length) == 2:
cpp_func_name += f'<{t}, {type_and_length[1]}>'
else:
return None
else:
if py_func not in self._fgpu_types:
self.RaiseError(tree,
f"'{py_func}' is not a valid FLAME GPU type")
t = self._fgpu_types[py_func]
cpp_func_name += f'<{t}>'
return cpp_func_name
def fill(self, text=''):
"""Indent a piece of text, according to the current indentation level"""
self.f.write('\n' + ' ' * self._indent + text)
def write(self, text):
"""Append a piece of text to the current line."""
self.f.write(str(text))
def enter(self):
"""Print '{', and increase the indentation."""
self.write('{')
self._indent += 1
def leave(self):
"""Decrease the indentation level and Print '}'"""
self._indent -= 1
self.fill('}')
def dispatch(self, tree):
"""Dispatcher function, dispatching tree type T to method _T."""
if isinstance(tree, list):
for t in tree:
self.dispatch(t)
return
meth = getattr(self, '_' + tree.__class__.__name__)
meth(tree)
def RaiseWarning(self, tree, str):
warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')
def RaiseError(self, tree, str):
raise CodeGenException(
f'Error ({tree.lineno}, {tree.col_offset}): {str}')
def dispatchMacroEnvFunction(self, tree, tree_parent):
"""
Function will handle a getMacroEnvironment function (assuming it is correctly formatted (by checking with _deviceVariableFunctionName first))
"""
cpp_func_name = 'getMacroProperty'
py_func = tree.attr
py_type = py_func[len(cpp_func_name):]
if py_type not in self._fgpu_types:
self.RaiseError(tree, f"'{py_type}' is not a valid FLAME GPU type")
t = self._fgpu_types[py_type]
cpp_func_name += f'<{t}'
if not tree_parent.args:
self.RaiseError(tree,
f" Macro environment function '{py_func}' is expected to have some arguments."
)
if len(tree_parent.args) > 1:
bounds = tree_parent.args[1:]
for i in bounds:
if isinstance(i, ast.Num):
if not isinstance(i.n, int):
self.RaiseError(tree,
f" Macro environment function argument '{i}' should be an integer value."
)
cpp_func_name += f', {i.n}'
else:
if not isinstance(i, ast.Constant):
self.RaiseError(tree,
f" Macro environment function argument '{i}' should be an constant value (or Num in Python <3.8)."
)
if not isinstance(i.value, int):
self.RaiseError(tree,
f" Macro environment function argument '{i}' should be an integer value."
)
cpp_func_name += f', {i.value}'
del tree_parent.args[1:]
cpp_func_name += '>'
self.write(cpp_func_name)
def dispatchFGPUFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`
Type hinting is required to translate a type into a FLAME GPU Message type implementation
"""
self._locals = ['pyflamegpu']
if len(tree.args.args) != 2:
self.RaiseError(tree,
'Expected two FLAME GPU function arguments (input message and output message)'
)
if not tree.args.args[0].annotation:
self.RaiseError(tree.args.args[0],
'Message input requires a supported type annotation')
if not isinstance(tree.args.args[0].annotation, ast.Attribute):
self.RaiseError(tree.args.args[0],
'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[0].annotation.value, ast.Name):
self.RaiseError(tree.args.args[0],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
input_message_attr = tree.args.args[0
].annotation.value.id + '.' + tree.args.args[0].annotation.attr
if input_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[0],
'Message input type annotation not a supported message type')
self._input_message_var = tree.args.args[0].arg
self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')
self.write(', ')
if not tree.args.args[1].annotation:
self.RaiseError(tree.args.args[1],
'Message output requires a supported type annotation')
if not isinstance(tree.args.args[1].annotation, ast.Attribute):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
if not isinstance(tree.args.args[1].annotation.value, ast.Name):
self.RaiseError(tree.args.args[1],
'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'
)
output_message_attr = tree.args.args[1
].annotation.value.id + '.' + tree.args.args[1].annotation.attr
if output_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[1],
'Message output type annotation not a supported message type')
self._output_message_var = tree.args.args[1].arg
self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')
def dispatchType(self, tree):
"""
There is a limited set of types and formats of type description supported. Types can be either;
1) A python built in type of int or float, or
2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16
This function translates and a catches unsupported types but does not translate a function call (i.e. cast)
"""
if isinstance(tree, ast.Name):
if tree.id not in self.basic_arg_types:
self.RaiseError(tree, 'Not a supported type')
self.write(tree.id)
elif isinstance(tree, ast.Attribute):
if not isinstance(tree.value, ast.Name):
self.RaiseError(tree, 'Not a supported type')
if not (tree.value.id == 'numpy' or tree.value.id == 'np'):
self.RaiseError(tree, 'Not a supported type')
if tree.attr not in self.numpytypes:
self.RaiseError(tree, 'Not a supported numpy type')
self.write(self.numpytypes[tree.attr])
else:
self.RaiseError(tree, 'Not a supported type')
def dispatchFGPUDeviceFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU device function. Arguments must use type hinting to be translated to cpp.
"""
self._locals = ['pyflamegpu']
first = True
annotation = None
for arg in tree.args.args:
if not arg.annotation:
self.RaiseError(arg,
'Device function argument requires type annotation')
if not first:
self.write(', ')
self.dispatchType(arg.annotation)
self.write(f' {arg.arg}')
self._locals.append(arg.arg)
first = False
def dispatchMessageIteratorCall(self, tree):
"""
Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())
Using this function avoid using the global call one which may accept member function calls to things that are not iterators.
"""
if isinstance(tree.func, ast.Name):
self.write(f'FLAMEGPU->{tree.func.id}')
if isinstance(tree.func, ast.Attribute):
if isinstance(tree.func.value, ast.Name):
if not tree.func.attr in self.fgpu_input_msg_iter_funcs:
self.RaiseError(tree,
f"Message input loop iterator '{tree.func.attr}' is not supported."
)
self.write(f'FLAMEGPU->{tree.func.value.id}.{tree.func.attr}')
else:
self.RaiseError(tree,
'Message input loop iterator format incorrect.')
self.write('(')
self._CallArguments(tree)
self.write(')')
def dispatchMessageLoop(self, tree):
"""
This is a special case of a range based for loop in which iterator item returns a const referecne to the message.
Any user specified message value can be used.
"""
self.fill('for (const auto& ')
self.dispatch(tree.target)
self.write(' : ')
if isinstance(tree.iter, ast.Name):
if not tree.iter.id == self._input_message_var:
self.RaiseError(t,
f"Message input loop requires use of '{self._input_message_var}' as iterator."
)
self.write(f'FLAMEGPU->{self._input_message_var}')
elif isinstance(tree.iter, ast.Call):
self.dispatchMessageIteratorCall(tree.iter)
else:
self.RaiseError(tree,
f'Message input loop iterator in unsupported format')
self.write(')')
self._message_iterator_var = tree.target.id
self.enter()
self.dispatch(tree.body)
self.leave()
self._message_iterator_var = None
def dispatchMemberFunction(self, t, t_parent):
"""
A very limited set of function calls to members are supported so these are fully evaluated here.
t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)
Function calls permitted are;
* pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.
* message_input.function - a call to the message input variable (the name of which is specified in the function definition)
* msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)
* message_output.function - a call to the message output variable (the name of which is specified in the function definition)
* pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.
* math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`
* numpy.type - Any numpy types are translated to static casts
"""
if not hasattr(t, 'value'):
self.RaiseError(t, f'Function call is in an unsupported format.')
if isinstance(t.value, ast.Attribute):
t_parent.call_type = None
if not isinstance(t.value.value, ast.Name):
self.RaiseError(t, 'Unknown or unsupported nested attribute')
if (t.value.value.id == 'pyflamegpu' and t.value.attr ==
'environment'):
self.write('FLAMEGPU->environment.')
if t.attr in self.fgpu_env_funcs:
self.write(t.attr)
elif t.attr.startswith('getProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getProperty'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment property function."
)
self.write(py_func)
t_parent.call_type = 'Environment'
elif t.attr.startswith('getMacroProperty'):
py_func = self._deviceVariableFunctionName(t, [
'getMacroProperty'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function."
)
self.dispatchMacroEnvFunction(t, t_parent)
t_parent.call_type = 'MacroEnvironment'
else:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.environment object"
)
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':
self.write('FLAMEGPU->random.')
if t.attr in self.fgpu_rand_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'uniform', 'normal', 'logNormal'], allow_lengths=False)
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.random object"
)
self.write(py_func)
t_parent.call_type = 'Random'
elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':
self.write('FLAMEGPU->agent_out.')
if t.attr in self.fgpu_agent_out_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu.agent_out object"
)
self.write(py_func)
t_parent.call_type = 'AgentOut'
else:
self.RaiseError(t,
f'Unknown or unsupported nested attribute in {t.value.value.id}'
)
elif isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
self.write('FLAMEGPU->')
if t.attr in self.fgpu_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable', 'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in pyflamegpu object"
)
self.write(py_func)
elif t.value.id == self._input_message_var:
if t.attr in self.fgpu_input_msg_funcs:
self.write(f'FLAMEGPU->{self._input_message_var}.')
self.write(t.attr)
else:
self.RaiseError(t,
f"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'"
)
elif self._message_iterator_var and t.value.id == self._message_iterator_var:
self.write(f'{self._message_iterator_var}.')
if t.attr in self.fgpu_input_msg_iter_var_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'getVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object"
)
self.write(py_func)
elif t.value.id == self._output_message_var:
self.write('FLAMEGPU->message_out.')
if t.attr in self.fgpu_output_msg_funcs:
self.write(t.attr)
else:
py_func = self._deviceVariableFunctionName(t, [
'setVariable'])
if not py_func:
self.RaiseError(t,
f"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object"
)
self.write(py_func)
elif t.value.id == 'math':
self.write(t.attr)
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(f'static_cast<{self.numpytypes[t.attr]}>')
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
elif t.value.id in self._locals:
self.write(f'{t.value.id}.{t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifier not supported")
elif isinstance(t.value, ast.Call):
self.dispatchMemberFunction(t.value.func, t.value)
if t.value.call_type != 'MacroEnvironment':
self.RaiseError(t, f'Function call {t.attr} is not supported')
if not t.attr in self.fgpu_env_macro_funcs:
self.RaiseError(t,
f'Function {t.attr} is not a valid macro environment function'
)
self.write('(')
self._CallArguments(t.value)
self.write(')')
self.write(f'.{t.attr}')
else:
self.RaiseError(t, 'Unsupported function call syntax')
def _Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Expression(self, tree):
self.dispatch(tree.body)
def _Expr(self, tree):
"""
Same as a standard python expression but ends with semicolon
"""
if isinstance(tree.value, ast.Constant):
if isinstance(tree.value.value, str):
return
elif isinstance(tree.value, ast.Str):
return
self.fill()
self.dispatch(tree.value)
self.write(';')
def _NamedExpr(self, tree):
"""
No such concept in C++. Standard assignment can be used in any location.
"""
self.write('(')
self.dispatch(tree.target)
self.write(' = ')
self.dispatch(tree.value)
self.write(')')
def _Import(self, t):
self.RaiseError(t, 'Importing of modules not supported')
def _ImportFrom(self, t):
self.RaiseError(t, 'Importing of modules not supported')
def _Assign(self, t):
"""
Assignment will use the auto type to define a variable at first use else will perform standard assignment.
Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.
Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.
"""
if len(t.targets) > 1:
self.RaiseError(t, 'Assignment to multiple targets not supported')
if not isinstance(t.targets[0], ast.Name):
self.RaiseError(t,
'Assignment to complex expressions not supported')
self.fill()
if t.targets[0].id not in self._locals:
self.write('auto ')
self._locals.append(t.targets[0].id)
self.dispatch(t.targets[0])
self.write(' = ')
self.dispatch(t.value)
self.write(';')
def _AugAssign(self, t):
"""
Similar to assignment in terms of restrictions. E.g. Allow only single named variable assignments.
Also requires the named variable to already exist in scope.
"""
if not isinstance(t.target, ast.Name):
self.RaiseError(t,
'Augmented assignment to complex expressions not supported')
if t.target.id not in self._locals:
self.RaiseError(t,
'Augmented assignment not permitted on variables not already assigned previously'
)
self.fill()
self.dispatch(t.target)
self.write(' ' + self.binop[t.op.__class__.__name__] + '= ')
self.dispatch(t.value)
self.write(';')
def _AnnAssign(self, t):
if not isinstance(t.target, ast.Name):
self.RaiseError(t,
'Augmented assignment to complex expressions not supported')
self.fill()
self.dispatchType(t.annotation)
self.write(' ')
self.dispatch(t.target)
if t.value:
self.write(' = ')
self.dispatch(t.value)
self.write(';')
def _Return(self, t):
"""
Standard cpp like return with semicolon.
"""
self.fill('return')
if t.value:
self.write(' ')
self.dispatch(t.value)
self.write(';')
def _Pass(self, t):
self.fill(';')
def _Break(self, t):
self.fill('break;')
def _Continue(self, t):
self.fill('continue;')
def _Delete(self, t):
self.RaiseError(t, 'Deletion not supported')
def _Assert(self, t):
"""
cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy
"""
self.RaiseError(t, 'Assert not supported')
def _Exec(self, t):
self.RaiseError(t, 'Exec not supported')
def _Print(self, t):
"""
This is old school python printing so no need to support
"""
self.RaiseError(t, 'Print not supported')
def _Global(self, t):
self.RaiseError(t, "Use of 'global' not supported")
def _Nonlocal(self, t):
self.RaiseError(t, "Use of 'nonlocal' not supported")
def _Await(self, t):
self.RaiseError(t, 'Await not supported')
def _Yield(self, t):
self.RaiseError(t, 'Yield not supported')
def _YieldFrom(self, t):
self.RaiseError(t, 'Yield from not supported')
def _Raise(self, t):
"""
Exceptions are obviously supported in cpp but not in CUDA device code
"""
self.RaiseError(t, 'Exception raising not supported')
def _Try(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _TryExcept(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _TryFinally(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _ExceptHandler(self, t):
self.RaiseError(t, 'Exceptions not supported')
def _ClassDef(self, t):
self.RaiseError(t, 'Class definitions not supported')
def _FunctionDef(self, t):
"""
Checks the decorators of the function definition much must be either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'.
Each is then processed in a different way using a specific dispatcher.
Function calls are actually checked and only permitted (or user defined) function calls are supported.
"""
self.write('\n')
if len(t.decorator_list) != 1 or not isinstance(t.decorator_list[0],
ast.Attribute):
self.RaiseError(t,
"Function definitions require a single pyflamegpu decorator of either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'"
)
if t.decorator_list[0].attr == 'agent_function' and t.decorator_list[0
].value.id == 'pyflamegpu':
if getattr(t, 'returns', False):
self.RaiseWarning(t,
"Function definition return type not supported on 'pyflamegpu.agent_function'"
)
self.fill(f'FLAMEGPU_AGENT_FUNCTION({t.name}, ')
self.dispatchFGPUFunctionArgs(t)
self.write(')')
elif t.decorator_list[0
].attr == 'device_function' and t.decorator_list[0
].value.id == 'pyflamegpu':
self.fill(f'FLAMEGPU_DEVICE_FUNCTION ')
if t.returns:
self.dispatchType(t.returns)
else:
self.write('void')
self.write(f' {t.name}(')
self.dispatchFGPUDeviceFunctionArgs(t)
self.write(')')
self._device_functions.append(t.name)
elif t.decorator_list[0
].attr == 'agent_function_condition' and t.decorator_list[0
].value.id == 'pyflamegpu':
if not hasattr(t, 'returns'):
self.RaiseError(t,
"Agent function conditions must have a 'bool' return type specified as a return type annotation"
)
if not isinstance(t.returns, ast.Name):
self.RaiseError(t,
"Agent function conditions return type must be 'bool'")
if t.returns.id is not 'bool':
self.RaiseError(t,
"Agent function conditions return type must be 'bool'")
if t.args.args:
self.RaiseWarning(t,
'Agent function conditions does not support arguments. These will be discarded.'
)
self.fill(f'FLAMEGPU_AGENT_FUNCTION_CONDITION({t.name})')
else:
self.RaiseError(t,
"Function definition uses an unsupported decorator. Must use either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'"
)
self.enter()
self.dispatch(t.body)
self.leave()
def _AsyncFunctionDef(self, t):
self.RaiseError(t, 'Async functions not supported')
def _For(self, t):
"""
Two type for for loop are supported. Either;
1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'
2) A range based for loop with 1 to 3 arguments which is converted into a c style loop
"""
if isinstance(t.iter, ast.Name):
if t.iter.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
"Range based for loops only support message iteration using 'message_in' iterator"
)
elif t.orelse:
self.RaiseError(t, 'For else not supported')
elif isinstance(t.iter, ast.Call):
if isinstance(t.iter.func, ast.Name):
if t.iter.func.id == self._input_message_var:
self.dispatchMessageLoop(t)
elif t.iter.func.id == 'range':
if len(t.iter.args) == 1:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=0;')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 2:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('++)')
elif len(t.iter.args) == 3:
self.fill(f'for (int ')
self.dispatch(t.target)
self.write('=')
self.dispatch(t.iter.args[0])
self.write(';')
self.dispatch(t.target)
self.write('<')
self.dispatch(t.iter.args[1])
self.write(';')
self.dispatch(t.target)
self.write('+=')
self.dispatch(t.iter.args[2])
self.write(')')
else:
self.RaiseError(t,
"Range based for loops requires use of 'range' function with arguments and not keywords"
)
self.enter()
self.dispatch(t.body)
self.leave()
else:
self.RaiseError(t,
"Range based for loops only support calls to the 'range' function"
)
elif isinstance(t.iter.func, ast.Attribute):
if t.iter.func.value.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t,
'Range based for loops only support calling members of message input variable'
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
else:
self.RaiseError(t,
"Range based for loops only support message iteration or use of 'range'"
)
def _AsyncFor(self, t):
self.RaiseError(t, 'Async for not supported')
def _If(self, t):
"""
Fairly straightforward translation to if, else if, else format
"""
self.fill('if (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0],
ast.If):
t = t.orelse[0]
self.fill('else if (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.fill('else')
self.enter()
self.dispatch(t.orelse)
self.leave()
def _While(self, t):
"""
Straightforward translation to c style while loop
"""
self.fill('while (')
self.dispatch(t.test)
self.write(')')
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.RaiseError(t, 'While else not supported')
def _With(self, t):
self.RaiseError(t, 'With not supported')
def _AsyncWith(self, t):
self.RaiseError(t, 'Async with not supported')
def _Bytes(self, t):
self.RaiseError(t, 'Byte strings and Bytes function not supported')
def _Str(self, tree):
self.write(f'"{tree.s}"')
def _JoinedStr(self, t):
self.RaiseError(t, 'Joined strings not supported')
<|reserved_special_token_0|>
def _fstring_JoinedStr(self, t, write):
self.RaiseError(t, 'F strings not supported')
<|reserved_special_token_0|>
def _fstring_Constant(self, t, write):
self.RaiseError(t, 'F strings not supported')
def _fstring_FormattedValue(self, t, write):
self.RaiseError(t, 'F strings not supported')
def _Name(self, t):
"""
Everything ends up as a Name once it is an identifier
"""
self.write(t.id)
def _NameConstant(self, t):
if t.value == None:
self.write(0)
elif t.value:
self.write('true')
else:
self.write('false')
def _Repr(self, t):
self.RaiseError(t, 'Repr not supported')
def _Constant(self, t):
"""
Restrict most types of constant except for numeric types and constant strings
Picks up some obvious conversions such as None and Bools
"""
value = t.value
if isinstance(value, tuple):
self.RaiseError(t, 'Tuples not supported')
if isinstance(value, dict):
self.RaiseError(t, 'Dictionaries not supported')
if isinstance(value, list):
self.RaiseError(t, 'Lists not supported')
elif value is Ellipsis:
self.RaiseError(t, 'Ellipsis not supported')
elif isinstance(value, str):
self.write(f'"{value}"')
elif isinstance(value, (bytes, bytearray)):
self.RaiseError(t, 'Byte strings and Bytes function not supported')
elif isinstance(value, bool):
if value:
self.write('true')
else:
self.write('false')
elif value == None:
self.write(0)
else:
self.write(repr(value))
def _Num(self, t):
self.write(repr(t.n))
def _List(self, t):
self.RaiseError(t, 'Lists not supported')
def _ListComp(self, t):
self.RaiseError(t, 'List comprehension not supported')
def _GeneratorExp(self, t):
self.RaiseError(t, 'Generator expressions not supported')
def _SetComp(self, t):
self.RaiseError(t, 'Set comprehension not supported')
def _DictComp(self, t):
self.RaiseError(t, 'Dictionary comprehension not supported')
def _comprehension(self, t):
self.RaiseError(t, 'Comprehension not supported')
def _IfExp(self, t):
"""
Equivalent to a ternary operator
"""
self.dispatch(t.test)
self.write(' ? ')
self.dispatch(t.body)
self.write(' : ')
self.dispatch(t.orelse)
def _Set(self, t):
self.RaiseError(t, 'Sets not supported')
def _Dict(self, t):
self.RaiseError(t, 'Dictionaries not supported')
def _Tuple(self, t):
self.RaiseError(t, 'Tuples not supported')
<|reserved_special_token_0|>
def _UnaryOp(self, t):
"""
Translate to C equivalent opertaors
"""
self.write('(')
self.write(self.unop[t.op.__class__.__name__])
self.dispatch(t.operand)
self.write(')')
<|reserved_special_token_0|>
def _BinOp(self, t):
"""
Python style pow and floordiv are not supported so translate to a function call.
No matrix mul support.
"""
op_name = t.op.__class__.__name__
if op_name == 'Pow':
self.write('pow(')
self.dispatch(t.left)
self.write(', ')
self.dispatch(t.right)
self.write(')')
elif op_name == 'FloorDiv':
self.write('floor(')
self.dispatch(t.left)
self.write('/')
self.dispatch(t.right)
self.write(')')
elif op_name == 'MatMult':
self.RaiseError(t, 'Matrix multiplier operator not supported')
else:
self.write('(')
self.dispatch(t.left)
self.write(' ' + self.binop[op_name] + ' ')
self.dispatch(t.right)
self.write(')')
<|reserved_special_token_0|>
def _Compare(self, t):
self.dispatch(t.left)
for o, e in zip(t.ops, t.comparators):
if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':
self.RaiseError(t, 'In and NotIn operators not supported')
self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')
self.dispatch(e)
<|reserved_special_token_0|>
def _BoolOp(self, t):
"""
Translate to logical and/or operators in C
"""
self.write('(')
s = ' %s ' % self.boolops[t.op.__class__]
interleave(lambda : self.write(s), self.dispatch, t.values)
self.write(')')
def _Attribute(self, t):
"""
A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.
Attributes supported are only;
* pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.
* math.constant - Any supported math constants are translated to C definition versions
"""
func_dict = None
if isinstance(t.value, ast.Name):
if t.value.id == 'pyflamegpu':
if t.attr in self.fgpu_attrs:
self.write('flamegpu::')
self.write(t.attr)
else:
self.RaiseError(t,
f"Attribute '{t.attr}' does not exist in pyflamegpu object"
)
elif t.value.id == 'math':
if t.attr in self.mathconsts:
self.write(self.mathconsts[t.attr])
else:
self.RaiseError(t, f"Unsupported math constant '{t.attr}'")
elif t.value.id == 'numpy' or t.value.id == 'np':
if t.attr in self.numpytypes:
self.write(self.numpytypes[t.attr])
else:
self.RaiseError(t, f'Unsupported numpy type {t.attr}')
else:
self.RaiseError(t,
f"Global '{t.value.id}' identifiers not supported")
else:
self.RaiseError(t, 'Unsupported attribute')
def _CallArguments(self, t):
comma = False
for e in t.args:
if comma:
self.write(', ')
else:
comma = True
self.dispatch(e)
if len(t.keywords):
self.RaiseWarning(t, 'Keyword argument not supported. Ignored.')
if sys.version_info[:2] < (3, 5):
if t.starargs:
self.RaiseWarning(t, 'Starargs not supported. Ignored.')
if t.kwargs:
self.RaiseWarning(t, 'Kwargs not supported. Ignored.')
def _Call(self, t):
"""
Some basic checks are undertaken on calls to ensure that the function being called is either a builtin or defined device function.
A special dispatcher is required
"""
funcs = self._device_functions + self.pythonbuiltins + [self.
_input_message_var]
if isinstance(t.func, ast.Name):
if t.func.id not in funcs:
self.RaiseWarning(t,
'Function call is not a defined FLAME GPU device function or a supported python built in.'
)
self.dispatch(t.func)
elif isinstance(t.func, ast.Lambda):
self.dispatch(t.func)
else:
self.dispatchMemberFunction(t.func, t)
self.write('(')
self._CallArguments(t)
self.write(')')
def _Subscript(self, t):
"""
Arrays are not supported but subscript allows accessing array like variables which is required for macro environment properties (e.g. a[0][1][2])
Obvious limitation is no slicing type syntax (e.g. a[:2])
"""
self.dispatch(t.value)
self.write('[')
self.dispatch(t.slice)
self.write(']')
def _Starred(self, t):
self.RaiseError(t, 'Starred values not supported')
def _Ellipsis(self, t):
self.RaiseError(t, 'Ellipsis values not supported')
def _Index(self, t):
self.RaiseError(t, 'Index values not supported')
def _Slice(self, t):
self.RaiseError(t, 'Slicing values not supported')
def _ExtSlice(self, t):
self.RaiseError(t, 'ExtSlice values not supported')
def _arg(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, 'Arguments should already have been processed')
def _arguments(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, 'Arguments should already have been processed')
def _keyword(self, t):
self.RaiseError(t, 'Keywords are not supported')
def _Lambda(self, t):
self.RaiseError(t, 'Lambda is not supported')
def _alias(self, t):
self.RaiseError(t, 'Aliasing is not supported')
def _withitem(self, t):
self.RaiseError(t, 'With not supported')
<|reserved_special_token_1|>
from __future__ import print_function, unicode_literals
import sys
import ast
import os
import tokenize
import warnings
from io import StringIO
def interleave(inter, f, seq):
"""Call f on each item in seq, calling inter() in between.
"""
seq = iter(seq)
try:
f(next(seq))
except StopIteration:
pass
else:
for x in seq:
inter()
f(x)
class CodeGenException(Exception):
""" Generic exception for errors raised in code generation """
pass
class CodeGenerator:
"""Methods in this class recursively traverse an AST and
output source code for the abstract syntax; original formatting
is disregarded. """
# represents built in functions
pythonbuiltins = ["abs", "float", "int"]
# basic types
basic_arg_types = ['float', 'int']
# supported math constansts
mathconsts = {"pi": "M_PI",
"e": "M_E",
"inf": "INFINITY",
"nan": "NAN",
}
# support for most numpy types except complex numbers and float>64bit
numpytypes = {"byte": "char",
"ubyte": "unsigned char",
"short": "short",
"ushort": "unsigned short",
"intc": "int",
"uintc": "unsigned int",
"uint": "unisgned int",
"longlong": "long long",
"ulonglong": "unsigned long long",
"half": "half", # cuda supported
"single": "float",
"double": "double",
"longdouble": "long double",
"bool_": "bool",
"bool8": "bool",
# sized aliases
"int_": "long",
"int8": "int8_t",
"int16": "int16_t",
"int32": "int32_t",
"int64": "int64_t",
"intp": "intptr_t",
"uint_": "long",
"uint8": "uint8_t",
"uint16": "uint16_t",
"uint32": "uint32_t",
"uint64": "uint64_t",
"uintp": "uintptr_t",
"float_": "float",
"float16": "half",
"float32": "float",
"float64": "double"
}
# getVariableType and setVariableType functions are added dynamically
fgpu_funcs = [ "getID", "getStepCounter", "getIndex" ]
fgpu_attrs = ["ALIVE", "DEAD"]
fgpu_input_msg_funcs = ["radius", "at"] # functions that can be called on message_in that do NOT return iterators
fgpu_input_msg_iter_funcs = ["wrap", "vn", "vn_wrap"] # functions that can be called on message_in that do return iterators
fgpu_input_msg_iter_var_funcs = ["getIndex", "getVirtualX", "getVirtualY", "getVirtualZ"]
fgpu_output_msg_funcs = ["setLocation", "setKey", "setIndex"]
fgpu_agent_out_msg_funcs = ["getID"]
fgpu_env_funcs = ["containsProperty", "containsMacroProperty"]
fgpu_env_macro_funcs = ["exchange", "CAS", "min", "max"]
fgpu_rand_funcs = []
fgpu_message_types = ["pyflamegpu.MessageNone", "pyflamegpu.MessageBruteForce", "pyflamegpu.MessageBucket", "pyflamegpu.MessageSpatial2D", "pyflamegpu.MessageSpatial3D", "pyflamegpu.MessageArray", "pyflamegpu.MessageArray2D", "pyflamegpu.MessageArray3D"]
_fgpu_types = {"Float": "float",
"Double": "double",
"Int": "int",
"UInt": "unsigned int",
"Int8": "int_8",
"UInt8": "uint_8",
"Char": "char",
"UChar": "unsigned char",
"Int16": "int_16",
"UInt16": "uint_16",
"Int32": "int_32",
"UInt32": "uint_32",
"Int64": "int_64",
"UInt64": "uint_64"
}
def __init__(self, tree, file = sys.stdout):
"""CodeGenerator(tree, file=sys.stdout) -> None.
Print the source for tree to file."""
self.f = file
self.future_imports = []
self._indent = 0
# dict of locals used to determine if variable already exists in assignments
self._locals = ["pyflamegpu"]
self._device_functions = []
self._message_iterator_var = None # default
self._input_message_var = 'message_in' # default
self._output_message_var = 'message_out' # default
self.dispatch(tree)
print("", file=self.f)
self.f.flush()
def _deviceVariableFunctionName(self, tree, permitted_prefixes, allow_lengths = True):
"""
Gets the device function name by translating a typed Python version to a templated cpp version.
Python functions looks like getVariableFloatArray6 and translate to getVariable<float, 6>
This function will detect and test against a set of known types and also extract the Array length
This function returns None if the string is invalid in format but only throws an error if the format is correct but the type is invalid.
"""
cpp_func_name = ""
py_func = tree.attr
# extract function name start
for prefix in permitted_prefixes:
if py_func.startswith(prefix):
cpp_func_name = prefix
py_func = py_func[len(prefix):]
break # dont allow the else
else:
return None
# check type and lengths
if allow_lengths:
#split to get type and Array Length (This could **potentially** be looked up from the model description but current syntax is consistent with swig bindings)
type_and_length = py_func.split("Array")
if type_and_length[0] not in self._fgpu_types:
self.RaiseError(tree, f"'{type_and_length[0]}' is not a valid FLAME GPU type")
t = self._fgpu_types[type_and_length[0]]
# generate template args
if (len(type_and_length) == 1):
cpp_func_name += f"<{t}>"
elif (len(type_and_length) == 2):
cpp_func_name += f"<{t}, {type_and_length[1]}>"
else:
return None
else:
if py_func not in self._fgpu_types:
self.RaiseError(tree, f"'{py_func}' is not a valid FLAME GPU type")
t = self._fgpu_types[py_func]
cpp_func_name += f"<{t}>"
# return
return cpp_func_name
def fill(self, text = ""):
"Indent a piece of text, according to the current indentation level"
self.f.write("\n"+" "*self._indent + text)
def write(self, text):
"Append a piece of text to the current line."
self.f.write(str(text))
def enter(self):
"Print '{', and increase the indentation."
self.write("{")
self._indent += 1
def leave(self):
"Decrease the indentation level and Print '}'"
self._indent -= 1
self.fill("}")
def dispatch(self, tree):
"Dispatcher function, dispatching tree type T to method _T."
if isinstance(tree, list):
for t in tree:
self.dispatch(t)
return
meth = getattr(self, "_"+tree.__class__.__name__)
meth(tree)
def RaiseWarning(self, tree, str):
warnings.warn(f"Warning ({tree.lineno}, {tree.col_offset}): {str}")
def RaiseError(self, tree, str):
raise CodeGenException(f"Error ({tree.lineno}, {tree.col_offset}): {str}")
############### Cutsom Unparsing methods ###############
# These are special versions of the ast unparsing #
# dispatch functions. #
########################################################
def dispatchMacroEnvFunction(self, tree, tree_parent):
"""
Function will handle a getMacroEnvironment function (assuming it is correctly formatted (by checking with _deviceVariableFunctionName first))
"""
cpp_func_name = "getMacroProperty"
py_func = tree.attr
# extract type from function name
py_type = py_func[len(cpp_func_name):]
if py_type not in self._fgpu_types:
self.RaiseError(tree, f"'{py_type}' is not a valid FLAME GPU type")
# get cpp type
t = self._fgpu_types[py_type]
cpp_func_name += f"<{t}"
# mess with the parent to extract (and remove arguments so they dont end up in the argument list)
if not tree_parent.args :
self.RaiseError(tree, f" Macro environment function '{py_func}' is expected to have some arguments.")
# if more than one arg then the rest are bounds to translate
if len(tree_parent.args) > 1:
bounds = tree_parent.args[1:]
# process bounds by appending to cpp function template arguments
for i in bounds:
if isinstance(i, ast.Num): # num required for python 3.7
if not isinstance(i.n, int):
self.RaiseError(tree, f" Macro environment function argument '{i}' should be an integer value.")
cpp_func_name += f", {i.n}"
else: # all Python > 3.7
if not isinstance(i, ast.Constant):
self.RaiseError(tree, f" Macro environment function argument '{i}' should be an constant value (or Num in Python <3.8).")
if not isinstance(i.value, int):
self.RaiseError(tree, f" Macro environment function argument '{i}' should be an integer value.")
cpp_func_name += f", {i.value}"
# remove bounds from argument list (in place)
del tree_parent.args[1:]
cpp_func_name += ">"
self.write(cpp_func_name)
def dispatchFGPUFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`
Type hinting is required to translate a type into a FLAME GPU Message type implementation
"""
# reset the locals variable stack
self._locals = ["pyflamegpu"]
if len(tree.args.args) != 2:
self.RaiseError(tree, "Expected two FLAME GPU function arguments (input message and output message)")
# input message
if not tree.args.args[0].annotation:
self.RaiseError(tree.args.args[0], "Message input requires a supported type annotation")
if not isinstance(tree.args.args[0].annotation, ast.Attribute):
self.RaiseError(tree.args.args[0], "Message input type annotation should be an attribute of the form pyflamegpu.MessageType")
if not isinstance(tree.args.args[0].annotation.value, ast.Name):
self.RaiseError(tree.args.args[0], "Message output type annotation should be an attribute of the form pyflamegpu.MessageType")
input_message_attr = tree.args.args[0].annotation.value.id + "." + tree.args.args[0].annotation.attr
if input_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[0], "Message input type annotation not a supported message type")
self._input_message_var = tree.args.args[0].arg # store the message input variable name
self.write(f"flamegpu::{tree.args.args[0].annotation.attr}") # requires namespace
self.write(", ")
# output message
if not tree.args.args[1].annotation:
self.RaiseError(tree.args.args[1], "Message output requires a supported type annotation")
if not isinstance(tree.args.args[1].annotation, ast.Attribute):
self.RaiseError(tree.args.args[1], "Message output type annotation should be an attribute of the form pyflamegpu.MessageType")
if not isinstance(tree.args.args[1].annotation.value, ast.Name):
self.RaiseError(tree.args.args[1], "Message output type annotation should be an attribute of the form pyflamegpu.MessageType")
output_message_attr = tree.args.args[1].annotation.value.id + "." + tree.args.args[1].annotation.attr
if output_message_attr not in self.fgpu_message_types:
self.RaiseError(tree.args.args[1], "Message output type annotation not a supported message type")
self._output_message_var = tree.args.args[1].arg # store the message output variable name
self.write(f"flamegpu::{tree.args.args[1].annotation.attr}") # requires namespace
def dispatchType(self, tree):
"""
There is a limited set of types and formats of type description supported. Types can be either;
1) A python built in type of int or float, or
2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16
This function translates and a catches unsupported types but does not translate a function call (i.e. cast)
"""
if isinstance(tree, ast.Name):
if tree.id not in self.basic_arg_types:
self.RaiseError(tree, "Not a supported type")
self.write(tree.id)
elif isinstance(tree, ast.Attribute):
if not isinstance(tree.value, ast.Name) :
self.RaiseError(tree, "Not a supported type")
if not (tree.value.id == "numpy" or tree.value.id == "np"):
self.RaiseError(tree, "Not a supported type")
if tree.attr not in self.numpytypes:
self.RaiseError(tree, "Not a supported numpy type")
self.write(self.numpytypes[tree.attr])
else:
self.RaiseError(tree, "Not a supported type")
def dispatchFGPUDeviceFunctionArgs(self, tree):
"""
Handles arguments for a FLAME GPU device function. Arguments must use type hinting to be translated to cpp.
"""
# reset the locals variable stack
self._locals = ["pyflamegpu"]
# input message
first = True
annotation = None
for arg in tree.args.args:
# ensure that there is a type annotation
if not arg.annotation:
self.RaiseError(arg, "Device function argument requires type annotation")
# comma if not first
if not first:
self.write(", ")
self.dispatchType(arg.annotation)
self.write(f" {arg.arg}")
# add arg to local variable stack
self._locals.append(arg.arg)
first = False
def dispatchMessageIteratorCall(self, tree):
"""
Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())
Using this function avoid using the global call one which may accept member function calls to things that are not iterators.
"""
# simple case not a member function just an iterator with arguments
if isinstance(tree.func, ast.Name):
self.write(f"FLAMEGPU->{tree.func.id}")
if isinstance(tree.func, ast.Attribute) :
if isinstance(tree.func.value, ast.Name):
# check that the iterator is supported
if not tree.func.attr in self.fgpu_input_msg_iter_funcs:
self.RaiseError(tree, f"Message input loop iterator '{tree.func.attr}' is not supported.")
self.write(f"FLAMEGPU->{tree.func.value.id}.{tree.func.attr}")
else:
self.RaiseError(tree, "Message input loop iterator format incorrect.")
# handle function arguments
self.write("(")
self._CallArguments(tree)
self.write(")")
def dispatchMessageLoop(self, tree):
"""
This is a special case of a range based for loop in which iterator item returns a const referecne to the message.
Any user specified message value can be used.
"""
self.fill("for (const auto& ")
self.dispatch(tree.target)
self.write(" : ")
# if simple message iterator
if isinstance(tree.iter, ast.Name):
if not tree.iter.id == self._input_message_var:
self.RaiseError(t, f"Message input loop requires use of '{self._input_message_var}' as iterator.")
# write with prefix
self.write(f"FLAMEGPU->{self._input_message_var}")
# if it is a call then handle the different cases
elif isinstance(tree.iter, ast.Call):
self.dispatchMessageIteratorCall(tree.iter)
#otherwise not supported
else :
self.RaiseError(tree, f"Message input loop iterator in unsupported format")
self.write(")")
self._message_iterator_var = tree.target.id
self.enter()
self.dispatch(tree.body)
self.leave()
self._message_iterator_var = None
def dispatchMemberFunction(self, t, t_parent):
"""
A very limited set of function calls to members are supported so these are fully evaluated here.
t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)
Function calls permitted are;
* pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.
* message_input.function - a call to the message input variable (the name of which is specified in the function definition)
* msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)
* message_output.function - a call to the message output variable (the name of which is specified in the function definition)
* pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.
* math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`
* numpy.type - Any numpy types are translated to static casts
"""
# it could be possible that the Call object has no value property e.g. a()()
if not hasattr(t, "value"):
self.RaiseError(t, f"Function call is in an unsupported format.")
# Nested member functions (e.g. x.y.z())
if isinstance(t.value, ast.Attribute):
# store some information about the source of this function call in parent as this may be useful for validation in whatever has called this function
t_parent.call_type = None
# only nested attribute type is environment
if not isinstance(t.value.value, ast.Name):
self.RaiseError(t, "Unknown or unsupported nested attribute")
# pyflamegpu.environment
if t.value.value.id == "pyflamegpu" and t.value.attr == "environment":
# check it is a supported environment function
self.write("FLAMEGPU->environment.")
if t.attr in self.fgpu_env_funcs:
# proceed
self.write(t.attr)
else:
# simple getProperty type function
if t.attr.startswith('getProperty') :
# possible getter setter type function
py_func = self._deviceVariableFunctionName(t, ["getProperty"])
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' is not a supported pyflamegpu.environment property function.")
# write the getProperty type function
self.write(py_func)
t_parent.call_type = "Environment"
# need to catch case of getMacroProperty as arguments need to be translated into template parameters in cpp (and py_func can be ignored)
elif t.attr.startswith("getMacroProperty"):
# possible getter setter type function (Note: getMacroProperty only supports a subset of types but type checking is not performed. This is best left to the compiler.)
# no not permit lengths (e.g. Float4) as these will be passed as arguments
py_func = self._deviceVariableFunctionName(t, ["getMacroProperty"], allow_lengths=False)
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function.")
# handle case
self.dispatchMacroEnvFunction(t, t_parent)
t_parent.call_type = "MacroEnvironment"
else:
self.RaiseError(t, f"Function '{t.attr}' does not exist in pyflamegpu.environment object")
# pyflamegpu.random
elif t.value.value.id == "pyflamegpu" and t.value.attr == "random":
# check it is a supported random function
self.write("FLAMEGPU->random.")
if t.attr in self.fgpu_rand_funcs:
# proceed
self.write(t.attr)
else:
# possible getter setter type function
py_func = self._deviceVariableFunctionName(t, ["uniform", "normal", "logNormal"], allow_lengths=False)
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' does not exist in pyflamegpu.random object")
# proceed
self.write(py_func)
t_parent.call_type = "Random"
elif t.value.value.id == "pyflamegpu" and t.value.attr == "agent_out":
# check it is a supported agent_out function
self.write("FLAMEGPU->agent_out.")
if t.attr in self.fgpu_agent_out_msg_funcs:
# proceed
self.write(t.attr)
else:
# possible getter setter type function
py_func = self._deviceVariableFunctionName(t, ["setVariable"])
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' does not exist in pyflamegpu.agent_out object")
# proceed
self.write(py_func)
t_parent.call_type = "AgentOut"
else:
self.RaiseError(t, f"Unknown or unsupported nested attribute in {t.value.value.id}")
# Non nested member functions (e.g. x.y())
elif isinstance(t.value, ast.Name):
# pyflamegpu singleton
if t.value.id == "pyflamegpu":
# check for legit FGPU function calls
self.write("FLAMEGPU->")
if t.attr in self.fgpu_funcs:
# proceed
self.write(t.attr)
else:
# possible getter setter type function
py_func = self._deviceVariableFunctionName(t, ["getVariable", "setVariable"])
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' does not exist in pyflamegpu object")
# proceed
self.write(py_func)
# message_in function using whatever variable was named in function declaration (e.g radius)
elif t.value.id == self._input_message_var:
# only process functions on message_in that are not iterators
if t.attr in self.fgpu_input_msg_funcs:
self.write(f"FLAMEGPU->{self._input_message_var}.")
self.write(t.attr)
else:
self.RaiseError(t, f"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'")
# message input iterator arg
elif self._message_iterator_var and t.value.id == self._message_iterator_var:
self.write(f"{self._message_iterator_var}.")
# check for legit FGPU function calls and translate
if t.attr in self.fgpu_input_msg_iter_var_funcs:
# proceed
self.write(t.attr)
else:
# possible getter setter type function
py_func = self._deviceVariableFunctionName(t, ["getVariable"])
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object")
# proceed
self.write(py_func)
# message output arg
elif t.value.id == self._output_message_var:
# check for legit FGPU function calls and translate
self.write("FLAMEGPU->message_out.")
if t.attr in self.fgpu_output_msg_funcs:
# proceed
self.write(t.attr)
else:
# possible getter setter type function
py_func = self._deviceVariableFunctionName(t, ["setVariable"])
if not py_func:
self.RaiseError(t, f"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object")
# proceed
self.write(py_func)
# math functions (try them in raw function call format) or constants
elif t.value.id == "math":
self.write(t.attr)
# numpy types
elif t.value.id == "numpy" or t.value.id == "np":
if t.attr in self.numpytypes:
self.write(f"static_cast<{self.numpytypes[t.attr]}>")
else:
self.RaiseError(t, f"Unsupported numpy type {t.attr}")
# allow any call on any locals (too many cases to enforce without type checking)
elif t.value.id in self._locals:
self.write(f"{t.value.id}.{t.attr}")
else:
self.RaiseError(t, f"Global '{t.value.id}' identifier not supported")
# Call is a very nested situation which can occur only on macro environment properties. E.g. 'pyflamegpu.environment.getMacroPropertyInt('a').exchange(10)'
elif isinstance(t.value, ast.Call):
# handle the call by recursively calling this function to do the depth first execution of pyflamegpu.environment.getMacroPropertyInt('a')
self.dispatchMemberFunction(t.value.func, t.value)
# check that the handler was actually for macro environment
if t.value.call_type != "MacroEnvironment" :
self.RaiseError(t, f"Function call {t.attr} is not supported")
# now append the outer call by making sure the thing been called is a valid macro env function
if not t.attr in self.fgpu_env_macro_funcs:
self.RaiseError(t, f"Function {t.attr} is not a valid macro environment function")
# write inner call args
self.write("(")
self._CallArguments(t.value)
self.write(")")
# write outer function (call args will be completed by _Call)
self.write(f".{t.attr}")
else:
self.RaiseError(t, "Unsupported function call syntax")
############### Unparsing methods ######################
# There should be one method per concrete grammar type #
# Constructors should be grouped by sum type. Ideally, #
# this would follow the order in the grammar, but #
# currently doesn't. #
########################################################
def _Module(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Interactive(self, tree):
for stmt in tree.body:
self.dispatch(stmt)
def _Expression(self, tree):
self.dispatch(tree.body)
# stmt
def _Expr(self, tree):
"""
Same as a standard python expression but ends with semicolon
"""
# Catch odd case of multi line strings and doc strings which are Expr with a Constant string type value
if isinstance(tree.value, ast.Constant):
if isinstance(tree.value.value, str):
return
# catch special case of Python 3.7 Where doc string is a Str and not a Constant
elif isinstance(tree.value, ast.Str):
return
# otherwise treat like a normal expression
self.fill()
self.dispatch(tree.value)
self.write(";")
def _NamedExpr(self, tree):
"""
No such concept in C++. Standard assignment can be used in any location.
"""
self.write("(")
self.dispatch(tree.target)
self.write(" = ")
self.dispatch(tree.value)
self.write(")")
def _Import(self, t):
self.RaiseError(t, "Importing of modules not supported")
def _ImportFrom(self, t):
self.RaiseError(t, "Importing of modules not supported")
def _Assign(self, t):
"""
Assignment will use the auto type to define a variable at first use else will perform standard assignment.
Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.
Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.
"""
if len(t.targets) > 1:
self.RaiseError(t, "Assignment to multiple targets not supported")
if not isinstance(t.targets[0], ast.Name):
self.RaiseError(t, "Assignment to complex expressions not supported")
self.fill()
# check if target exists in locals
if t.targets[0].id not in self._locals :
self.write("auto ")
self._locals.append(t.targets[0].id)
self.dispatch(t.targets[0])
self.write(" = ")
self.dispatch(t.value)
self.write(";")
def _AugAssign(self, t):
"""
Similar to assignment in terms of restrictions. E.g. Allow only single named variable assignments.
Also requires the named variable to already exist in scope.
"""
if not isinstance(t.target, ast.Name):
self.RaiseError(t, "Augmented assignment to complex expressions not supported")
# check if target exists in locals
if t.target.id not in self._locals :
self.RaiseError(t, "Augmented assignment not permitted on variables not already assigned previously")
self.fill()
self.dispatch(t.target)
self.write(" "+self.binop[t.op.__class__.__name__]+"= ")
self.dispatch(t.value)
self.write(";")
def _AnnAssign(self, t):
if not isinstance(t.target, ast.Name):
self.RaiseError(t, "Augmented assignment to complex expressions not supported")
self.fill()
self.dispatchType(t.annotation)
self.write(" ")
self.dispatch(t.target)
if t.value:
self.write(" = ")
self.dispatch(t.value)
self.write(";")
def _Return(self, t):
"""
Standard cpp like return with semicolon.
"""
self.fill("return")
if t.value:
self.write(" ")
self.dispatch(t.value)
self.write(";")
def _Pass(self, t):
self.fill(";")
def _Break(self, t):
self.fill("break;")
def _Continue(self, t):
self.fill("continue;")
def _Delete(self, t):
self.RaiseError(t, "Deletion not supported")
def _Assert(self, t):
"""
cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy
"""
self.RaiseError(t, "Assert not supported")
def _Exec(self, t):
self.RaiseError(t, "Exec not supported")
def _Print(self, t):
"""
This is old school python printing so no need to support
"""
self.RaiseError(t, "Print not supported")
def _Global(self, t):
self.RaiseError(t, "Use of 'global' not supported")
def _Nonlocal(self, t):
self.RaiseError(t, "Use of 'nonlocal' not supported")
def _Await(self, t):
self.RaiseError(t, "Await not supported")
def _Yield(self, t):
self.RaiseError(t, "Yield not supported")
def _YieldFrom(self, t):
self.RaiseError(t, "Yield from not supported")
def _Raise(self, t):
"""
Exceptions are obviously supported in cpp but not in CUDA device code
"""
self.RaiseError(t, "Exception raising not supported")
def _Try(self, t):
self.RaiseError(t, "Exceptions not supported")
def _TryExcept(self, t):
self.RaiseError(t, "Exceptions not supported")
def _TryFinally(self, t):
self.RaiseError(t, "Exceptions not supported")
def _ExceptHandler(self, t):
self.RaiseError(t, "Exceptions not supported")
def _ClassDef(self, t):
self.RaiseError(t, "Class definitions not supported")
def _FunctionDef(self, t):
"""
Checks the decorators of the function definition much must be either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'.
Each is then processed in a different way using a specific dispatcher.
Function calls are actually checked and only permitted (or user defined) function calls are supported.
"""
self.write("\n")
# check decorators
if len(t.decorator_list) != 1 or not isinstance(t.decorator_list[0], ast.Attribute):
self.RaiseError(t, "Function definitions require a single pyflamegpu decorator of either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'")
# FLAMEGPU_AGENT_FUNCTION
if t.decorator_list[0].attr == 'agent_function' and t.decorator_list[0].value.id == 'pyflamegpu':
if getattr(t, "returns", False):
self.RaiseWarning(t, "Function definition return type not supported on 'pyflamegpu.agent_function'")
self.fill(f"FLAMEGPU_AGENT_FUNCTION({t.name}, ")
self.dispatchFGPUFunctionArgs(t)
self.write(")")
# FLAMEGPU_DEVICE_FUNCTION
elif t.decorator_list[0].attr == 'device_function' and t.decorator_list[0].value.id == 'pyflamegpu':
self.fill(f"FLAMEGPU_DEVICE_FUNCTION ")
if t.returns:
self.dispatchType(t.returns)
else:
self.write("void")
self.write(f" {t.name}(")
self.dispatchFGPUDeviceFunctionArgs(t)
self.write(")")
# add to list of defined functions that can be called
self._device_functions.append(t.name)
# FLAMEGPU_DEVICE_FUNCTION
elif t.decorator_list[0].attr == 'agent_function_condition' and t.decorator_list[0].value.id == 'pyflamegpu':
# check for return annotation
if not hasattr(t, "returns"):
self.RaiseError(t, "Agent function conditions must have a 'bool' return type specified as a return type annotation")
# check for return annotation type
if not isinstance(t.returns, ast.Name):
self.RaiseError(t, "Agent function conditions return type must be 'bool'")
if t.returns.id is not 'bool':
self.RaiseError(t, "Agent function conditions return type must be 'bool'")
# check to ensure no arguments (discard any with a warning)
if t.args.args:
self.RaiseWarning(t, "Agent function conditions does not support arguments. These will be discarded.")
# write the agent function macro
self.fill(f"FLAMEGPU_AGENT_FUNCTION_CONDITION({t.name})")
else:
self.RaiseError(t, "Function definition uses an unsupported decorator. Must use either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'")
self.enter()
self.dispatch(t.body)
self.leave()
def _AsyncFunctionDef(self, t):
self.RaiseError(t, "Async functions not supported")
def _For(self, t):
"""
Two type for for loop are supported. Either;
1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'
2) A range based for loop with 1 to 3 arguments which is converted into a c style loop
"""
# if message loop then process differently
if isinstance(t.iter, ast.Name):
if t.iter.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t, "Range based for loops only support message iteration using 'message_in' iterator")
# do not support for else
elif t.orelse:
self.RaiseError(t, "For else not supported")
# allow calls but only to range function
elif isinstance(t.iter, ast.Call):
# simple function call e.g. message_in() or range()
if isinstance(t.iter.func, ast.Name):
# catch case of message_input with arguments (e.g. spatial messaging)
if t.iter.func.id == self._input_message_var:
self.dispatchMessageLoop(t)
# otherwise permit only range based for loops
elif t.iter.func.id == "range":
# switch on different uses of range based on number of arguments
if len(t.iter.args) == 1:
self.fill(f"for (int ")
self.dispatch(t.target)
self.write("=0;")
self.dispatch(t.target)
self.write("<")
self.dispatch(t.iter.args[0])
self.write(";")
self.dispatch(t.target)
self.write("++)")
elif len(t.iter.args) == 2:
self.fill(f"for (int ")
self.dispatch(t.target)
self.write("=")
self.dispatch(t.iter.args[0])
self.write(";")
self.dispatch(t.target)
self.write("<")
self.dispatch(t.iter.args[1])
self.write(";")
self.dispatch(t.target)
self.write("++)")
elif len(t.iter.args) == 3:
self.fill(f"for (int ")
self.dispatch(t.target)
self.write("=")
self.dispatch(t.iter.args[0])
self.write(";")
self.dispatch(t.target)
self.write("<")
self.dispatch(t.iter.args[1])
self.write(";")
self.dispatch(t.target)
self.write("+=")
self.dispatch(t.iter.args[2])
self.write(")")
else:
self.RaiseError(t, "Range based for loops requires use of 'range' function with arguments and not keywords")
self.enter()
self.dispatch(t.body)
self.leave()
else:
self.RaiseError(t, "Range based for loops only support calls to the 'range' function")
# member function call can only be on message_in.func() type call.
elif isinstance(t.iter.func, ast.Attribute):
# must be an attribute (e.g. calling a member of message_in)
if t.iter.func.value.id == self._input_message_var:
self.dispatchMessageLoop(t)
else:
self.RaiseError(t, "Range based for loops only support calling members of message input variable")
else:
self.RaiseError(t, "Range based for loops only support message iteration or use of 'range'")
else:
self.RaiseError(t, "Range based for loops only support message iteration or use of 'range'")
def _AsyncFor(self, t):
self.RaiseError(t, "Async for not supported")
def _If(self, t):
"""
Fairly straightforward translation to if, else if, else format
"""
self.fill("if (")
self.dispatch(t.test)
self.write(")")
self.enter()
self.dispatch(t.body)
self.leave()
# collapse nested ifs into equivalent elifs.
while (t.orelse and len(t.orelse) == 1 and
isinstance(t.orelse[0], ast.If)):
t = t.orelse[0]
self.fill("else if (")
self.dispatch(t.test)
self.write(")")
self.enter()
self.dispatch(t.body)
self.leave()
# final else
if t.orelse:
self.fill("else")
self.enter()
self.dispatch(t.orelse)
self.leave()
def _While(self, t):
"""
Straightforward translation to c style while loop
"""
self.fill("while (")
self.dispatch(t.test)
self.write(")")
self.enter()
self.dispatch(t.body)
self.leave()
if t.orelse:
self.RaiseError(t, "While else not supported")
def _With(self, t):
self.RaiseError(t, "With not supported")
def _AsyncWith(self, t):
self.RaiseError(t, "Async with not supported")
# expr
def _Bytes(self, t):
self.RaiseError(t, "Byte strings and Bytes function not supported")
def _Str(self, tree):
# force writing in double quotes
self.write(f'"{tree.s}"')
def _JoinedStr(self, t):
self.RaiseError(t, "Joined strings not supported")
def _FormattedValue(self, t):
self.RaiseError(t, "Formatted strings not supported")
def _fstring_JoinedStr(self, t, write):
self.RaiseError(t, "F strings not supported")
def _fstring_Str(self, t, write):
self.RaiseError(t, "F strings not supported")
def _fstring_Constant(self, t, write):
self.RaiseError(t, "F strings not supported")
def _fstring_FormattedValue(self, t, write):
self.RaiseError(t, "F strings not supported")
def _Name(self, t):
"""
Everything ends up as a Name once it is an identifier
"""
self.write(t.id)
def _NameConstant(self, t):
# Required only for Python 3.7
if t.value == None:
self.write(0)
elif t.value:
self.write("true")
else:
self.write("false")
def _Repr(self, t):
self.RaiseError(t, "Repr not supported")
def _Constant(self, t):
"""
Restrict most types of constant except for numeric types and constant strings
Picks up some obvious conversions such as None and Bools
"""
value = t.value
if isinstance(value, tuple):
self.RaiseError(t, "Tuples not supported")
if isinstance(value, dict):
self.RaiseError(t, "Dictionaries not supported")
if isinstance(value, list):
self.RaiseError(t, "Lists not supported")
elif value is Ellipsis: # instead of `...` for Py2 compatibility
self.RaiseError(t, "Ellipsis not supported")
elif isinstance(value, str):
self.write(f'"{value}"')
elif isinstance(value, (bytes, bytearray)): # reject bytes strings e.g. b'123'
self.RaiseError(t, "Byte strings and Bytes function not supported")
elif isinstance(value, bool):
if value:
self.write("true")
else:
self.write("false")
elif value == None:
self.write(0)
else:
self.write(repr(value))
def _Num(self, t):
self.write(repr(t.n))
def _List(self, t):
self.RaiseError(t, "Lists not supported")
def _ListComp(self, t):
self.RaiseError(t, "List comprehension not supported")
def _GeneratorExp(self, t):
self.RaiseError(t, "Generator expressions not supported")
def _SetComp(self, t):
self.RaiseError(t, "Set comprehension not supported")
def _DictComp(self, t):
self.RaiseError(t, "Dictionary comprehension not supported")
def _comprehension(self, t):
self.RaiseError(t, "Comprehension not supported")
def _IfExp(self, t):
"""
Equivalent to a ternary operator
"""
self.dispatch(t.test)
self.write(" ? ")
self.dispatch(t.body)
self.write(" : ")
self.dispatch(t.orelse)
def _Set(self, t):
self.RaiseError(t, "Sets not supported")
def _Dict(self, t):
self.RaiseError(t, "Dictionaries not supported")
def _Tuple(self, t):
self.RaiseError(t, "Tuples not supported")
unop = {"Invert":"~", "Not": "!", "UAdd":"+", "USub":"-"}
def _UnaryOp(self, t):
"""
Translate to C equivalent opertaors
"""
self.write("(")
self.write(self.unop[t.op.__class__.__name__])
self.dispatch(t.operand)
self.write(")")
binop = { "Add":"+", "Sub":"-", "Mult":"*", "MatMult":"@", "Div":"/", "Mod":"%",
"LShift":"<<", "RShift":">>", "BitOr":"|", "BitXor":"^", "BitAnd":"&",
"FloorDiv":"//", "Pow": "**"}
def _BinOp(self, t):
"""
Python style pow and floordiv are not supported so translate to a function call.
No matrix mul support.
"""
op_name = t.op.__class__.__name__
# translate pow into function call (no float version)
if op_name == "Pow":
self.write("pow(")
self.dispatch(t.left)
self.write(", ")
self.dispatch(t.right)
self.write(")")
# translate floor div into function call (no float version)
elif op_name == "FloorDiv":
self.write("floor(")
self.dispatch(t.left)
self.write("/")
self.dispatch(t.right)
self.write(")")
elif op_name == "MatMult":
self.RaiseError(t, "Matrix multiplier operator not supported")
else:
self.write("(")
self.dispatch(t.left)
self.write(" " + self.binop[op_name] + " ")
self.dispatch(t.right)
self.write(")")
cmpops = {"Eq":"==", "NotEq":"!=", "Lt":"<", "LtE":"<=", "Gt":">", "GtE":">=",
"Is":"==", "IsNot":"!=", "In":"in", "NotIn":"not in"}
def _Compare(self, t):
self.dispatch(t.left)
for o, e in zip(t.ops, t.comparators):
# detect list ops
if o.__class__.__name__ == "In" or o.__class__.__name__ == "NotIn":
self.RaiseError(t, "In and NotIn operators not supported")
self.write(" " + self.cmpops[o.__class__.__name__] + " ")
self.dispatch(e)
boolops = {ast.And: '&&', ast.Or: '||'}
def _BoolOp(self, t):
"""
Translate to logical and/or operators in C
"""
self.write("(")
s = " %s " % self.boolops[t.op.__class__]
interleave(lambda: self.write(s), self.dispatch, t.values)
self.write(")")
def _Attribute(self,t):
"""
A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.
Attributes supported are only;
* pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.
* math.constant - Any supported math constants are translated to C definition versions
"""
# Only a limited set of globals supported
func_dict = None
# pyflamegpu singleton
if isinstance(t.value, ast.Name):
if t.value.id == "pyflamegpu":
if t.attr in self.fgpu_attrs:
# proceed
self.write("flamegpu::")
self.write(t.attr)
else:
self.RaiseError(t, f"Attribute '{t.attr}' does not exist in pyflamegpu object")
# math functions (try them in raw function call format) or constants
elif t.value.id == "math":
if t.attr in self.mathconsts:
self.write(self.mathconsts[t.attr])
else:
self.RaiseError(t, f"Unsupported math constant '{t.attr}'")
# numpy types
elif t.value.id == "numpy" or t.value.id == "np":
# not sure how a numpy attribute would be used without function call or type hint but translate anyway
if t.attr in self.numpytypes:
self.write(self.numpytypes[t.attr])
else:
self.RaiseError(t, f"Unsupported numpy type {t.attr}")
else:
self.RaiseError(t, f"Global '{t.value.id}' identifiers not supported")
else:
self.RaiseError(t, "Unsupported attribute")
def _CallArguments(self, t):
comma = False
for e in t.args:
if comma: self.write(", ")
else: comma = True
self.dispatch(e)
if len(t.keywords):
self.RaiseWarning(t, "Keyword argument not supported. Ignored.")
if sys.version_info[:2] < (3, 5):
if t.starargs:
self.RaiseWarning(t, "Starargs not supported. Ignored.")
if t.kwargs:
self.RaiseWarning(t, "Kwargs not supported. Ignored.")
def _Call(self, t):
"""
Some basic checks are undertaken on calls to ensure that the function being called is either a builtin or defined device function.
A special dispatcher is required
"""
# check calls but let attributes check in their own dispatcher
funcs = self._device_functions + self.pythonbuiltins + [self._input_message_var] # message_input variable is a valid function name as certain message types have arguments on iterator
if isinstance(t.func, ast.Name):
if (t.func.id not in funcs):
self.RaiseWarning(t, "Function call is not a defined FLAME GPU device function or a supported python built in.")
# dispatch even if warning raised
self.dispatch(t.func)
elif isinstance(t.func, ast.Lambda):
self.dispatch(t.func) # not supported
else:
# special handler for dispatching member function calls
# This would otherwise be an attribute
self.dispatchMemberFunction(t.func, t)
self.write("(")
self._CallArguments(t)
self.write(")")
def _Subscript(self, t):
"""
Arrays are not supported but subscript allows accessing array like variables which is required for macro environment properties (e.g. a[0][1][2])
Obvious limitation is no slicing type syntax (e.g. a[:2])
"""
self.dispatch(t.value)
self.write("[")
self.dispatch(t.slice)
self.write("]")
def _Starred(self, t):
self.RaiseError(t, "Starred values not supported")
# slice
def _Ellipsis(self, t):
self.RaiseError(t, "Ellipsis values not supported")
def _Index(self, t):
self.RaiseError(t, "Index values not supported")
def _Slice(self, t):
self.RaiseError(t, "Slicing values not supported")
def _ExtSlice(self, t):
self.RaiseError(t, "ExtSlice values not supported")
# argument
def _arg(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, "Arguments should already have been processed")
# others
def _arguments(self, t):
"""
Arguments should be processed by a custom dispatcher and it should not be possible to get here
"""
self.RaiseError(t, "Arguments should already have been processed")
def _keyword(self, t):
self.RaiseError(t, "Keywords are not supported")
def _Lambda(self, t):
self.RaiseError(t, "Lambda is not supported")
def _alias(self, t):
self.RaiseError(t, "Aliasing is not supported")
def _withitem(self, t):
self.RaiseError(t, "With not supported")
|
flexible
|
{
"blob_id": "8443d208a6a6bef82240235eeadbf6f8eaf77bcb",
"index": 2995,
"step-1": "<mask token>\n\n\nclass CodeGenerator:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, tree, file=sys.stdout):\n \"\"\"CodeGenerator(tree, file=sys.stdout) -> None.\n Print the source for tree to file.\"\"\"\n self.f = file\n self.future_imports = []\n self._indent = 0\n self._locals = ['pyflamegpu']\n self._device_functions = []\n self._message_iterator_var = None\n self._input_message_var = 'message_in'\n self._output_message_var = 'message_out'\n self.dispatch(tree)\n print('', file=self.f)\n self.f.flush()\n <mask token>\n\n def fill(self, text=''):\n \"\"\"Indent a piece of text, according to the current indentation level\"\"\"\n self.f.write('\\n' + ' ' * self._indent + text)\n <mask token>\n\n def enter(self):\n \"\"\"Print '{', and increase the indentation.\"\"\"\n self.write('{')\n self._indent += 1\n\n def leave(self):\n \"\"\"Decrease the indentation level and Print '}'\"\"\"\n self._indent -= 1\n self.fill('}')\n <mask token>\n\n def RaiseWarning(self, tree, str):\n warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')\n\n def RaiseError(self, tree, str):\n raise CodeGenException(\n f'Error ({tree.lineno}, {tree.col_offset}): {str}')\n <mask token>\n\n def dispatchFGPUFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`\n Type hinting is required to translate a type into a FLAME GPU Message type implementation\n \"\"\"\n self._locals = ['pyflamegpu']\n if len(tree.args.args) != 2:\n self.RaiseError(tree,\n 'Expected two FLAME GPU function arguments (input message and output message)'\n )\n if not tree.args.args[0].annotation:\n self.RaiseError(tree.args.args[0],\n 'Message input requires a supported type annotation')\n if not isinstance(tree.args.args[0].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[0].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[0],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n input_message_attr = tree.args.args[0\n ].annotation.value.id + '.' + tree.args.args[0].annotation.attr\n if input_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation not a supported message type')\n self._input_message_var = tree.args.args[0].arg\n self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')\n self.write(', ')\n if not tree.args.args[1].annotation:\n self.RaiseError(tree.args.args[1],\n 'Message output requires a supported type annotation')\n if not isinstance(tree.args.args[1].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[1].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n output_message_attr = tree.args.args[1\n ].annotation.value.id + '.' + tree.args.args[1].annotation.attr\n if output_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation not a supported message type')\n self._output_message_var = tree.args.args[1].arg\n self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')\n\n def dispatchType(self, tree):\n \"\"\"\n There is a limited set of types and formats of type description supported. Types can be either;\n 1) A python built in type of int or float, or\n 2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16\n This function translates and a catches unsupported types but does not translate a function call (i.e. cast)\n \"\"\"\n if isinstance(tree, ast.Name):\n if tree.id not in self.basic_arg_types:\n self.RaiseError(tree, 'Not a supported type')\n self.write(tree.id)\n elif isinstance(tree, ast.Attribute):\n if not isinstance(tree.value, ast.Name):\n self.RaiseError(tree, 'Not a supported type')\n if not (tree.value.id == 'numpy' or tree.value.id == 'np'):\n self.RaiseError(tree, 'Not a supported type')\n if tree.attr not in self.numpytypes:\n self.RaiseError(tree, 'Not a supported numpy type')\n self.write(self.numpytypes[tree.attr])\n else:\n self.RaiseError(tree, 'Not a supported type')\n <mask token>\n <mask token>\n\n def dispatchMessageLoop(self, tree):\n \"\"\"\n This is a special case of a range based for loop in which iterator item returns a const referecne to the message.\n Any user specified message value can be used.\n \"\"\"\n self.fill('for (const auto& ')\n self.dispatch(tree.target)\n self.write(' : ')\n if isinstance(tree.iter, ast.Name):\n if not tree.iter.id == self._input_message_var:\n self.RaiseError(t,\n f\"Message input loop requires use of '{self._input_message_var}' as iterator.\"\n )\n self.write(f'FLAMEGPU->{self._input_message_var}')\n elif isinstance(tree.iter, ast.Call):\n self.dispatchMessageIteratorCall(tree.iter)\n else:\n self.RaiseError(tree,\n f'Message input loop iterator in unsupported format')\n self.write(')')\n self._message_iterator_var = tree.target.id\n self.enter()\n self.dispatch(tree.body)\n self.leave()\n self._message_iterator_var = None\n\n def dispatchMemberFunction(self, t, t_parent):\n \"\"\"\n A very limited set of function calls to members are supported so these are fully evaluated here.\n t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)\n Function calls permitted are;\n * pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.\n * message_input.function - a call to the message input variable (the name of which is specified in the function definition)\n * msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)\n * message_output.function - a call to the message output variable (the name of which is specified in the function definition)\n * pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.\n * math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`\n * numpy.type - Any numpy types are translated to static casts\n \"\"\"\n if not hasattr(t, 'value'):\n self.RaiseError(t, f'Function call is in an unsupported format.')\n if isinstance(t.value, ast.Attribute):\n t_parent.call_type = None\n if not isinstance(t.value.value, ast.Name):\n self.RaiseError(t, 'Unknown or unsupported nested attribute')\n if (t.value.value.id == 'pyflamegpu' and t.value.attr ==\n 'environment'):\n self.write('FLAMEGPU->environment.')\n if t.attr in self.fgpu_env_funcs:\n self.write(t.attr)\n elif t.attr.startswith('getProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getProperty'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment property function.\"\n )\n self.write(py_func)\n t_parent.call_type = 'Environment'\n elif t.attr.startswith('getMacroProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getMacroProperty'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function.\"\n )\n self.dispatchMacroEnvFunction(t, t_parent)\n t_parent.call_type = 'MacroEnvironment'\n else:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.environment object\"\n )\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':\n self.write('FLAMEGPU->random.')\n if t.attr in self.fgpu_rand_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'uniform', 'normal', 'logNormal'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.random object\"\n )\n self.write(py_func)\n t_parent.call_type = 'Random'\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':\n self.write('FLAMEGPU->agent_out.')\n if t.attr in self.fgpu_agent_out_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.agent_out object\"\n )\n self.write(py_func)\n t_parent.call_type = 'AgentOut'\n else:\n self.RaiseError(t,\n f'Unknown or unsupported nested attribute in {t.value.value.id}'\n )\n elif isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n self.write('FLAMEGPU->')\n if t.attr in self.fgpu_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable', 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu object\"\n )\n self.write(py_func)\n elif t.value.id == self._input_message_var:\n if t.attr in self.fgpu_input_msg_funcs:\n self.write(f'FLAMEGPU->{self._input_message_var}.')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'\"\n )\n elif self._message_iterator_var and t.value.id == self._message_iterator_var:\n self.write(f'{self._message_iterator_var}.')\n if t.attr in self.fgpu_input_msg_iter_var_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object\"\n )\n self.write(py_func)\n elif t.value.id == self._output_message_var:\n self.write('FLAMEGPU->message_out.')\n if t.attr in self.fgpu_output_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object\"\n )\n self.write(py_func)\n elif t.value.id == 'math':\n self.write(t.attr)\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(f'static_cast<{self.numpytypes[t.attr]}>')\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n elif t.value.id in self._locals:\n self.write(f'{t.value.id}.{t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifier not supported\")\n elif isinstance(t.value, ast.Call):\n self.dispatchMemberFunction(t.value.func, t.value)\n if t.value.call_type != 'MacroEnvironment':\n self.RaiseError(t, f'Function call {t.attr} is not supported')\n if not t.attr in self.fgpu_env_macro_funcs:\n self.RaiseError(t,\n f'Function {t.attr} is not a valid macro environment function'\n )\n self.write('(')\n self._CallArguments(t.value)\n self.write(')')\n self.write(f'.{t.attr}')\n else:\n self.RaiseError(t, 'Unsupported function call syntax')\n\n def _Module(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Interactive(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Expression(self, tree):\n self.dispatch(tree.body)\n <mask token>\n <mask token>\n <mask token>\n\n def _ImportFrom(self, t):\n self.RaiseError(t, 'Importing of modules not supported')\n\n def _Assign(self, t):\n \"\"\"\n Assignment will use the auto type to define a variable at first use else will perform standard assignment.\n Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.\n Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.\n \"\"\"\n if len(t.targets) > 1:\n self.RaiseError(t, 'Assignment to multiple targets not supported')\n if not isinstance(t.targets[0], ast.Name):\n self.RaiseError(t,\n 'Assignment to complex expressions not supported')\n self.fill()\n if t.targets[0].id not in self._locals:\n self.write('auto ')\n self._locals.append(t.targets[0].id)\n self.dispatch(t.targets[0])\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _Continue(self, t):\n self.fill('continue;')\n <mask token>\n\n def _Assert(self, t):\n \"\"\"\n cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy\n \"\"\"\n self.RaiseError(t, 'Assert not supported')\n <mask token>\n\n def _Print(self, t):\n \"\"\"\n This is old school python printing so no need to support\n \"\"\"\n self.RaiseError(t, 'Print not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _Yield(self, t):\n self.RaiseError(t, 'Yield not supported')\n\n def _YieldFrom(self, t):\n self.RaiseError(t, 'Yield from not supported')\n <mask token>\n <mask token>\n\n def _TryExcept(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _TryFinally(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n <mask token>\n\n def _ClassDef(self, t):\n self.RaiseError(t, 'Class definitions not supported')\n <mask token>\n\n def _AsyncFunctionDef(self, t):\n self.RaiseError(t, 'Async functions not supported')\n\n def _For(self, t):\n \"\"\"\n Two type for for loop are supported. Either;\n 1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'\n 2) A range based for loop with 1 to 3 arguments which is converted into a c style loop\n \"\"\"\n if isinstance(t.iter, ast.Name):\n if t.iter.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration using 'message_in' iterator\"\n )\n elif t.orelse:\n self.RaiseError(t, 'For else not supported')\n elif isinstance(t.iter, ast.Call):\n if isinstance(t.iter.func, ast.Name):\n if t.iter.func.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n elif t.iter.func.id == 'range':\n if len(t.iter.args) == 1:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=0;')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 2:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 3:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('+=')\n self.dispatch(t.iter.args[2])\n self.write(')')\n else:\n self.RaiseError(t,\n \"Range based for loops requires use of 'range' function with arguments and not keywords\"\n )\n self.enter()\n self.dispatch(t.body)\n self.leave()\n else:\n self.RaiseError(t,\n \"Range based for loops only support calls to the 'range' function\"\n )\n elif isinstance(t.iter.func, ast.Attribute):\n if t.iter.func.value.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n 'Range based for loops only support calling members of message input variable'\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n <mask token>\n <mask token>\n\n def _While(self, t):\n \"\"\"\n Straightforward translation to c style while loop\n \"\"\"\n self.fill('while (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.RaiseError(t, 'While else not supported')\n <mask token>\n <mask token>\n\n def _Bytes(self, t):\n self.RaiseError(t, 'Byte strings and Bytes function not supported')\n <mask token>\n\n def _JoinedStr(self, t):\n self.RaiseError(t, 'Joined strings not supported')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _NameConstant(self, t):\n if t.value == None:\n self.write(0)\n elif t.value:\n self.write('true')\n else:\n self.write('false')\n\n def _Repr(self, t):\n self.RaiseError(t, 'Repr not supported')\n <mask token>\n <mask token>\n\n def _List(self, t):\n self.RaiseError(t, 'Lists not supported')\n <mask token>\n\n def _GeneratorExp(self, t):\n self.RaiseError(t, 'Generator expressions not supported')\n\n def _SetComp(self, t):\n self.RaiseError(t, 'Set comprehension not supported')\n\n def _DictComp(self, t):\n self.RaiseError(t, 'Dictionary comprehension not supported')\n\n def _comprehension(self, t):\n self.RaiseError(t, 'Comprehension not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _Tuple(self, t):\n self.RaiseError(t, 'Tuples not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _BinOp(self, t):\n \"\"\"\n Python style pow and floordiv are not supported so translate to a function call.\n No matrix mul support.\n \"\"\"\n op_name = t.op.__class__.__name__\n if op_name == 'Pow':\n self.write('pow(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'FloorDiv':\n self.write('floor(')\n self.dispatch(t.left)\n self.write('/')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'MatMult':\n self.RaiseError(t, 'Matrix multiplier operator not supported')\n else:\n self.write('(')\n self.dispatch(t.left)\n self.write(' ' + self.binop[op_name] + ' ')\n self.dispatch(t.right)\n self.write(')')\n <mask token>\n\n def _Compare(self, t):\n self.dispatch(t.left)\n for o, e in zip(t.ops, t.comparators):\n if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':\n self.RaiseError(t, 'In and NotIn operators not supported')\n self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')\n self.dispatch(e)\n <mask token>\n <mask token>\n\n def _Attribute(self, t):\n \"\"\"\n A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.\n Attributes supported are only;\n * pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.\n * math.constant - Any supported math constants are translated to C definition versions\n \"\"\"\n func_dict = None\n if isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n if t.attr in self.fgpu_attrs:\n self.write('flamegpu::')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Attribute '{t.attr}' does not exist in pyflamegpu object\"\n )\n elif t.value.id == 'math':\n if t.attr in self.mathconsts:\n self.write(self.mathconsts[t.attr])\n else:\n self.RaiseError(t, f\"Unsupported math constant '{t.attr}'\")\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(self.numpytypes[t.attr])\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifiers not supported\")\n else:\n self.RaiseError(t, 'Unsupported attribute')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _Ellipsis(self, t):\n self.RaiseError(t, 'Ellipsis values not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _arg(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, 'Arguments should already have been processed')\n <mask token>\n <mask token>\n <mask token>\n\n def _alias(self, t):\n self.RaiseError(t, 'Aliasing is not supported')\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass CodeGenerator:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, tree, file=sys.stdout):\n \"\"\"CodeGenerator(tree, file=sys.stdout) -> None.\n Print the source for tree to file.\"\"\"\n self.f = file\n self.future_imports = []\n self._indent = 0\n self._locals = ['pyflamegpu']\n self._device_functions = []\n self._message_iterator_var = None\n self._input_message_var = 'message_in'\n self._output_message_var = 'message_out'\n self.dispatch(tree)\n print('', file=self.f)\n self.f.flush()\n <mask token>\n\n def fill(self, text=''):\n \"\"\"Indent a piece of text, according to the current indentation level\"\"\"\n self.f.write('\\n' + ' ' * self._indent + text)\n <mask token>\n\n def enter(self):\n \"\"\"Print '{', and increase the indentation.\"\"\"\n self.write('{')\n self._indent += 1\n\n def leave(self):\n \"\"\"Decrease the indentation level and Print '}'\"\"\"\n self._indent -= 1\n self.fill('}')\n <mask token>\n\n def RaiseWarning(self, tree, str):\n warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')\n\n def RaiseError(self, tree, str):\n raise CodeGenException(\n f'Error ({tree.lineno}, {tree.col_offset}): {str}')\n <mask token>\n\n def dispatchFGPUFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`\n Type hinting is required to translate a type into a FLAME GPU Message type implementation\n \"\"\"\n self._locals = ['pyflamegpu']\n if len(tree.args.args) != 2:\n self.RaiseError(tree,\n 'Expected two FLAME GPU function arguments (input message and output message)'\n )\n if not tree.args.args[0].annotation:\n self.RaiseError(tree.args.args[0],\n 'Message input requires a supported type annotation')\n if not isinstance(tree.args.args[0].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[0].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[0],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n input_message_attr = tree.args.args[0\n ].annotation.value.id + '.' + tree.args.args[0].annotation.attr\n if input_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation not a supported message type')\n self._input_message_var = tree.args.args[0].arg\n self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')\n self.write(', ')\n if not tree.args.args[1].annotation:\n self.RaiseError(tree.args.args[1],\n 'Message output requires a supported type annotation')\n if not isinstance(tree.args.args[1].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[1].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n output_message_attr = tree.args.args[1\n ].annotation.value.id + '.' + tree.args.args[1].annotation.attr\n if output_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation not a supported message type')\n self._output_message_var = tree.args.args[1].arg\n self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')\n\n def dispatchType(self, tree):\n \"\"\"\n There is a limited set of types and formats of type description supported. Types can be either;\n 1) A python built in type of int or float, or\n 2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16\n This function translates and a catches unsupported types but does not translate a function call (i.e. cast)\n \"\"\"\n if isinstance(tree, ast.Name):\n if tree.id not in self.basic_arg_types:\n self.RaiseError(tree, 'Not a supported type')\n self.write(tree.id)\n elif isinstance(tree, ast.Attribute):\n if not isinstance(tree.value, ast.Name):\n self.RaiseError(tree, 'Not a supported type')\n if not (tree.value.id == 'numpy' or tree.value.id == 'np'):\n self.RaiseError(tree, 'Not a supported type')\n if tree.attr not in self.numpytypes:\n self.RaiseError(tree, 'Not a supported numpy type')\n self.write(self.numpytypes[tree.attr])\n else:\n self.RaiseError(tree, 'Not a supported type')\n <mask token>\n\n def dispatchMessageIteratorCall(self, tree):\n \"\"\"\n Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())\n Using this function avoid using the global call one which may accept member function calls to things that are not iterators.\n \"\"\"\n if isinstance(tree.func, ast.Name):\n self.write(f'FLAMEGPU->{tree.func.id}')\n if isinstance(tree.func, ast.Attribute):\n if isinstance(tree.func.value, ast.Name):\n if not tree.func.attr in self.fgpu_input_msg_iter_funcs:\n self.RaiseError(tree,\n f\"Message input loop iterator '{tree.func.attr}' is not supported.\"\n )\n self.write(f'FLAMEGPU->{tree.func.value.id}.{tree.func.attr}')\n else:\n self.RaiseError(tree,\n 'Message input loop iterator format incorrect.')\n self.write('(')\n self._CallArguments(tree)\n self.write(')')\n\n def dispatchMessageLoop(self, tree):\n \"\"\"\n This is a special case of a range based for loop in which iterator item returns a const referecne to the message.\n Any user specified message value can be used.\n \"\"\"\n self.fill('for (const auto& ')\n self.dispatch(tree.target)\n self.write(' : ')\n if isinstance(tree.iter, ast.Name):\n if not tree.iter.id == self._input_message_var:\n self.RaiseError(t,\n f\"Message input loop requires use of '{self._input_message_var}' as iterator.\"\n )\n self.write(f'FLAMEGPU->{self._input_message_var}')\n elif isinstance(tree.iter, ast.Call):\n self.dispatchMessageIteratorCall(tree.iter)\n else:\n self.RaiseError(tree,\n f'Message input loop iterator in unsupported format')\n self.write(')')\n self._message_iterator_var = tree.target.id\n self.enter()\n self.dispatch(tree.body)\n self.leave()\n self._message_iterator_var = None\n\n def dispatchMemberFunction(self, t, t_parent):\n \"\"\"\n A very limited set of function calls to members are supported so these are fully evaluated here.\n t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)\n Function calls permitted are;\n * pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.\n * message_input.function - a call to the message input variable (the name of which is specified in the function definition)\n * msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)\n * message_output.function - a call to the message output variable (the name of which is specified in the function definition)\n * pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.\n * math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`\n * numpy.type - Any numpy types are translated to static casts\n \"\"\"\n if not hasattr(t, 'value'):\n self.RaiseError(t, f'Function call is in an unsupported format.')\n if isinstance(t.value, ast.Attribute):\n t_parent.call_type = None\n if not isinstance(t.value.value, ast.Name):\n self.RaiseError(t, 'Unknown or unsupported nested attribute')\n if (t.value.value.id == 'pyflamegpu' and t.value.attr ==\n 'environment'):\n self.write('FLAMEGPU->environment.')\n if t.attr in self.fgpu_env_funcs:\n self.write(t.attr)\n elif t.attr.startswith('getProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getProperty'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment property function.\"\n )\n self.write(py_func)\n t_parent.call_type = 'Environment'\n elif t.attr.startswith('getMacroProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getMacroProperty'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function.\"\n )\n self.dispatchMacroEnvFunction(t, t_parent)\n t_parent.call_type = 'MacroEnvironment'\n else:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.environment object\"\n )\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':\n self.write('FLAMEGPU->random.')\n if t.attr in self.fgpu_rand_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'uniform', 'normal', 'logNormal'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.random object\"\n )\n self.write(py_func)\n t_parent.call_type = 'Random'\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':\n self.write('FLAMEGPU->agent_out.')\n if t.attr in self.fgpu_agent_out_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.agent_out object\"\n )\n self.write(py_func)\n t_parent.call_type = 'AgentOut'\n else:\n self.RaiseError(t,\n f'Unknown or unsupported nested attribute in {t.value.value.id}'\n )\n elif isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n self.write('FLAMEGPU->')\n if t.attr in self.fgpu_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable', 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu object\"\n )\n self.write(py_func)\n elif t.value.id == self._input_message_var:\n if t.attr in self.fgpu_input_msg_funcs:\n self.write(f'FLAMEGPU->{self._input_message_var}.')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'\"\n )\n elif self._message_iterator_var and t.value.id == self._message_iterator_var:\n self.write(f'{self._message_iterator_var}.')\n if t.attr in self.fgpu_input_msg_iter_var_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object\"\n )\n self.write(py_func)\n elif t.value.id == self._output_message_var:\n self.write('FLAMEGPU->message_out.')\n if t.attr in self.fgpu_output_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object\"\n )\n self.write(py_func)\n elif t.value.id == 'math':\n self.write(t.attr)\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(f'static_cast<{self.numpytypes[t.attr]}>')\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n elif t.value.id in self._locals:\n self.write(f'{t.value.id}.{t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifier not supported\")\n elif isinstance(t.value, ast.Call):\n self.dispatchMemberFunction(t.value.func, t.value)\n if t.value.call_type != 'MacroEnvironment':\n self.RaiseError(t, f'Function call {t.attr} is not supported')\n if not t.attr in self.fgpu_env_macro_funcs:\n self.RaiseError(t,\n f'Function {t.attr} is not a valid macro environment function'\n )\n self.write('(')\n self._CallArguments(t.value)\n self.write(')')\n self.write(f'.{t.attr}')\n else:\n self.RaiseError(t, 'Unsupported function call syntax')\n\n def _Module(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Interactive(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Expression(self, tree):\n self.dispatch(tree.body)\n <mask token>\n <mask token>\n <mask token>\n\n def _ImportFrom(self, t):\n self.RaiseError(t, 'Importing of modules not supported')\n\n def _Assign(self, t):\n \"\"\"\n Assignment will use the auto type to define a variable at first use else will perform standard assignment.\n Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.\n Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.\n \"\"\"\n if len(t.targets) > 1:\n self.RaiseError(t, 'Assignment to multiple targets not supported')\n if not isinstance(t.targets[0], ast.Name):\n self.RaiseError(t,\n 'Assignment to complex expressions not supported')\n self.fill()\n if t.targets[0].id not in self._locals:\n self.write('auto ')\n self._locals.append(t.targets[0].id)\n self.dispatch(t.targets[0])\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _Continue(self, t):\n self.fill('continue;')\n <mask token>\n\n def _Assert(self, t):\n \"\"\"\n cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy\n \"\"\"\n self.RaiseError(t, 'Assert not supported')\n <mask token>\n\n def _Print(self, t):\n \"\"\"\n This is old school python printing so no need to support\n \"\"\"\n self.RaiseError(t, 'Print not supported')\n <mask token>\n\n def _Nonlocal(self, t):\n self.RaiseError(t, \"Use of 'nonlocal' not supported\")\n <mask token>\n\n def _Yield(self, t):\n self.RaiseError(t, 'Yield not supported')\n\n def _YieldFrom(self, t):\n self.RaiseError(t, 'Yield from not supported')\n <mask token>\n <mask token>\n\n def _TryExcept(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _TryFinally(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n <mask token>\n\n def _ClassDef(self, t):\n self.RaiseError(t, 'Class definitions not supported')\n <mask token>\n\n def _AsyncFunctionDef(self, t):\n self.RaiseError(t, 'Async functions not supported')\n\n def _For(self, t):\n \"\"\"\n Two type for for loop are supported. Either;\n 1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'\n 2) A range based for loop with 1 to 3 arguments which is converted into a c style loop\n \"\"\"\n if isinstance(t.iter, ast.Name):\n if t.iter.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration using 'message_in' iterator\"\n )\n elif t.orelse:\n self.RaiseError(t, 'For else not supported')\n elif isinstance(t.iter, ast.Call):\n if isinstance(t.iter.func, ast.Name):\n if t.iter.func.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n elif t.iter.func.id == 'range':\n if len(t.iter.args) == 1:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=0;')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 2:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 3:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('+=')\n self.dispatch(t.iter.args[2])\n self.write(')')\n else:\n self.RaiseError(t,\n \"Range based for loops requires use of 'range' function with arguments and not keywords\"\n )\n self.enter()\n self.dispatch(t.body)\n self.leave()\n else:\n self.RaiseError(t,\n \"Range based for loops only support calls to the 'range' function\"\n )\n elif isinstance(t.iter.func, ast.Attribute):\n if t.iter.func.value.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n 'Range based for loops only support calling members of message input variable'\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n <mask token>\n <mask token>\n\n def _While(self, t):\n \"\"\"\n Straightforward translation to c style while loop\n \"\"\"\n self.fill('while (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.RaiseError(t, 'While else not supported')\n <mask token>\n <mask token>\n\n def _Bytes(self, t):\n self.RaiseError(t, 'Byte strings and Bytes function not supported')\n <mask token>\n\n def _JoinedStr(self, t):\n self.RaiseError(t, 'Joined strings not supported')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _NameConstant(self, t):\n if t.value == None:\n self.write(0)\n elif t.value:\n self.write('true')\n else:\n self.write('false')\n\n def _Repr(self, t):\n self.RaiseError(t, 'Repr not supported')\n <mask token>\n <mask token>\n\n def _List(self, t):\n self.RaiseError(t, 'Lists not supported')\n <mask token>\n\n def _GeneratorExp(self, t):\n self.RaiseError(t, 'Generator expressions not supported')\n\n def _SetComp(self, t):\n self.RaiseError(t, 'Set comprehension not supported')\n\n def _DictComp(self, t):\n self.RaiseError(t, 'Dictionary comprehension not supported')\n\n def _comprehension(self, t):\n self.RaiseError(t, 'Comprehension not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _Tuple(self, t):\n self.RaiseError(t, 'Tuples not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _BinOp(self, t):\n \"\"\"\n Python style pow and floordiv are not supported so translate to a function call.\n No matrix mul support.\n \"\"\"\n op_name = t.op.__class__.__name__\n if op_name == 'Pow':\n self.write('pow(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'FloorDiv':\n self.write('floor(')\n self.dispatch(t.left)\n self.write('/')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'MatMult':\n self.RaiseError(t, 'Matrix multiplier operator not supported')\n else:\n self.write('(')\n self.dispatch(t.left)\n self.write(' ' + self.binop[op_name] + ' ')\n self.dispatch(t.right)\n self.write(')')\n <mask token>\n\n def _Compare(self, t):\n self.dispatch(t.left)\n for o, e in zip(t.ops, t.comparators):\n if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':\n self.RaiseError(t, 'In and NotIn operators not supported')\n self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')\n self.dispatch(e)\n <mask token>\n <mask token>\n\n def _Attribute(self, t):\n \"\"\"\n A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.\n Attributes supported are only;\n * pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.\n * math.constant - Any supported math constants are translated to C definition versions\n \"\"\"\n func_dict = None\n if isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n if t.attr in self.fgpu_attrs:\n self.write('flamegpu::')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Attribute '{t.attr}' does not exist in pyflamegpu object\"\n )\n elif t.value.id == 'math':\n if t.attr in self.mathconsts:\n self.write(self.mathconsts[t.attr])\n else:\n self.RaiseError(t, f\"Unsupported math constant '{t.attr}'\")\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(self.numpytypes[t.attr])\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifiers not supported\")\n else:\n self.RaiseError(t, 'Unsupported attribute')\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def _Ellipsis(self, t):\n self.RaiseError(t, 'Ellipsis values not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _arg(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, 'Arguments should already have been processed')\n <mask token>\n <mask token>\n <mask token>\n\n def _alias(self, t):\n self.RaiseError(t, 'Aliasing is not supported')\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass CodeGenerator:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, tree, file=sys.stdout):\n \"\"\"CodeGenerator(tree, file=sys.stdout) -> None.\n Print the source for tree to file.\"\"\"\n self.f = file\n self.future_imports = []\n self._indent = 0\n self._locals = ['pyflamegpu']\n self._device_functions = []\n self._message_iterator_var = None\n self._input_message_var = 'message_in'\n self._output_message_var = 'message_out'\n self.dispatch(tree)\n print('', file=self.f)\n self.f.flush()\n <mask token>\n\n def fill(self, text=''):\n \"\"\"Indent a piece of text, according to the current indentation level\"\"\"\n self.f.write('\\n' + ' ' * self._indent + text)\n\n def write(self, text):\n \"\"\"Append a piece of text to the current line.\"\"\"\n self.f.write(str(text))\n\n def enter(self):\n \"\"\"Print '{', and increase the indentation.\"\"\"\n self.write('{')\n self._indent += 1\n\n def leave(self):\n \"\"\"Decrease the indentation level and Print '}'\"\"\"\n self._indent -= 1\n self.fill('}')\n <mask token>\n\n def RaiseWarning(self, tree, str):\n warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')\n\n def RaiseError(self, tree, str):\n raise CodeGenException(\n f'Error ({tree.lineno}, {tree.col_offset}): {str}')\n\n def dispatchMacroEnvFunction(self, tree, tree_parent):\n \"\"\"\n Function will handle a getMacroEnvironment function (assuming it is correctly formatted (by checking with _deviceVariableFunctionName first))\n \"\"\"\n cpp_func_name = 'getMacroProperty'\n py_func = tree.attr\n py_type = py_func[len(cpp_func_name):]\n if py_type not in self._fgpu_types:\n self.RaiseError(tree, f\"'{py_type}' is not a valid FLAME GPU type\")\n t = self._fgpu_types[py_type]\n cpp_func_name += f'<{t}'\n if not tree_parent.args:\n self.RaiseError(tree,\n f\" Macro environment function '{py_func}' is expected to have some arguments.\"\n )\n if len(tree_parent.args) > 1:\n bounds = tree_parent.args[1:]\n for i in bounds:\n if isinstance(i, ast.Num):\n if not isinstance(i.n, int):\n self.RaiseError(tree,\n f\" Macro environment function argument '{i}' should be an integer value.\"\n )\n cpp_func_name += f', {i.n}'\n else:\n if not isinstance(i, ast.Constant):\n self.RaiseError(tree,\n f\" Macro environment function argument '{i}' should be an constant value (or Num in Python <3.8).\"\n )\n if not isinstance(i.value, int):\n self.RaiseError(tree,\n f\" Macro environment function argument '{i}' should be an integer value.\"\n )\n cpp_func_name += f', {i.value}'\n del tree_parent.args[1:]\n cpp_func_name += '>'\n self.write(cpp_func_name)\n\n def dispatchFGPUFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`\n Type hinting is required to translate a type into a FLAME GPU Message type implementation\n \"\"\"\n self._locals = ['pyflamegpu']\n if len(tree.args.args) != 2:\n self.RaiseError(tree,\n 'Expected two FLAME GPU function arguments (input message and output message)'\n )\n if not tree.args.args[0].annotation:\n self.RaiseError(tree.args.args[0],\n 'Message input requires a supported type annotation')\n if not isinstance(tree.args.args[0].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[0].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[0],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n input_message_attr = tree.args.args[0\n ].annotation.value.id + '.' + tree.args.args[0].annotation.attr\n if input_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation not a supported message type')\n self._input_message_var = tree.args.args[0].arg\n self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')\n self.write(', ')\n if not tree.args.args[1].annotation:\n self.RaiseError(tree.args.args[1],\n 'Message output requires a supported type annotation')\n if not isinstance(tree.args.args[1].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[1].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n output_message_attr = tree.args.args[1\n ].annotation.value.id + '.' + tree.args.args[1].annotation.attr\n if output_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation not a supported message type')\n self._output_message_var = tree.args.args[1].arg\n self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')\n\n def dispatchType(self, tree):\n \"\"\"\n There is a limited set of types and formats of type description supported. Types can be either;\n 1) A python built in type of int or float, or\n 2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16\n This function translates and a catches unsupported types but does not translate a function call (i.e. cast)\n \"\"\"\n if isinstance(tree, ast.Name):\n if tree.id not in self.basic_arg_types:\n self.RaiseError(tree, 'Not a supported type')\n self.write(tree.id)\n elif isinstance(tree, ast.Attribute):\n if not isinstance(tree.value, ast.Name):\n self.RaiseError(tree, 'Not a supported type')\n if not (tree.value.id == 'numpy' or tree.value.id == 'np'):\n self.RaiseError(tree, 'Not a supported type')\n if tree.attr not in self.numpytypes:\n self.RaiseError(tree, 'Not a supported numpy type')\n self.write(self.numpytypes[tree.attr])\n else:\n self.RaiseError(tree, 'Not a supported type')\n\n def dispatchFGPUDeviceFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU device function. Arguments must use type hinting to be translated to cpp.\n \"\"\"\n self._locals = ['pyflamegpu']\n first = True\n annotation = None\n for arg in tree.args.args:\n if not arg.annotation:\n self.RaiseError(arg,\n 'Device function argument requires type annotation')\n if not first:\n self.write(', ')\n self.dispatchType(arg.annotation)\n self.write(f' {arg.arg}')\n self._locals.append(arg.arg)\n first = False\n\n def dispatchMessageIteratorCall(self, tree):\n \"\"\"\n Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())\n Using this function avoid using the global call one which may accept member function calls to things that are not iterators.\n \"\"\"\n if isinstance(tree.func, ast.Name):\n self.write(f'FLAMEGPU->{tree.func.id}')\n if isinstance(tree.func, ast.Attribute):\n if isinstance(tree.func.value, ast.Name):\n if not tree.func.attr in self.fgpu_input_msg_iter_funcs:\n self.RaiseError(tree,\n f\"Message input loop iterator '{tree.func.attr}' is not supported.\"\n )\n self.write(f'FLAMEGPU->{tree.func.value.id}.{tree.func.attr}')\n else:\n self.RaiseError(tree,\n 'Message input loop iterator format incorrect.')\n self.write('(')\n self._CallArguments(tree)\n self.write(')')\n\n def dispatchMessageLoop(self, tree):\n \"\"\"\n This is a special case of a range based for loop in which iterator item returns a const referecne to the message.\n Any user specified message value can be used.\n \"\"\"\n self.fill('for (const auto& ')\n self.dispatch(tree.target)\n self.write(' : ')\n if isinstance(tree.iter, ast.Name):\n if not tree.iter.id == self._input_message_var:\n self.RaiseError(t,\n f\"Message input loop requires use of '{self._input_message_var}' as iterator.\"\n )\n self.write(f'FLAMEGPU->{self._input_message_var}')\n elif isinstance(tree.iter, ast.Call):\n self.dispatchMessageIteratorCall(tree.iter)\n else:\n self.RaiseError(tree,\n f'Message input loop iterator in unsupported format')\n self.write(')')\n self._message_iterator_var = tree.target.id\n self.enter()\n self.dispatch(tree.body)\n self.leave()\n self._message_iterator_var = None\n\n def dispatchMemberFunction(self, t, t_parent):\n \"\"\"\n A very limited set of function calls to members are supported so these are fully evaluated here.\n t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)\n Function calls permitted are;\n * pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.\n * message_input.function - a call to the message input variable (the name of which is specified in the function definition)\n * msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)\n * message_output.function - a call to the message output variable (the name of which is specified in the function definition)\n * pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.\n * math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`\n * numpy.type - Any numpy types are translated to static casts\n \"\"\"\n if not hasattr(t, 'value'):\n self.RaiseError(t, f'Function call is in an unsupported format.')\n if isinstance(t.value, ast.Attribute):\n t_parent.call_type = None\n if not isinstance(t.value.value, ast.Name):\n self.RaiseError(t, 'Unknown or unsupported nested attribute')\n if (t.value.value.id == 'pyflamegpu' and t.value.attr ==\n 'environment'):\n self.write('FLAMEGPU->environment.')\n if t.attr in self.fgpu_env_funcs:\n self.write(t.attr)\n elif t.attr.startswith('getProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getProperty'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment property function.\"\n )\n self.write(py_func)\n t_parent.call_type = 'Environment'\n elif t.attr.startswith('getMacroProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getMacroProperty'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function.\"\n )\n self.dispatchMacroEnvFunction(t, t_parent)\n t_parent.call_type = 'MacroEnvironment'\n else:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.environment object\"\n )\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':\n self.write('FLAMEGPU->random.')\n if t.attr in self.fgpu_rand_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'uniform', 'normal', 'logNormal'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.random object\"\n )\n self.write(py_func)\n t_parent.call_type = 'Random'\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':\n self.write('FLAMEGPU->agent_out.')\n if t.attr in self.fgpu_agent_out_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.agent_out object\"\n )\n self.write(py_func)\n t_parent.call_type = 'AgentOut'\n else:\n self.RaiseError(t,\n f'Unknown or unsupported nested attribute in {t.value.value.id}'\n )\n elif isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n self.write('FLAMEGPU->')\n if t.attr in self.fgpu_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable', 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu object\"\n )\n self.write(py_func)\n elif t.value.id == self._input_message_var:\n if t.attr in self.fgpu_input_msg_funcs:\n self.write(f'FLAMEGPU->{self._input_message_var}.')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'\"\n )\n elif self._message_iterator_var and t.value.id == self._message_iterator_var:\n self.write(f'{self._message_iterator_var}.')\n if t.attr in self.fgpu_input_msg_iter_var_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object\"\n )\n self.write(py_func)\n elif t.value.id == self._output_message_var:\n self.write('FLAMEGPU->message_out.')\n if t.attr in self.fgpu_output_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object\"\n )\n self.write(py_func)\n elif t.value.id == 'math':\n self.write(t.attr)\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(f'static_cast<{self.numpytypes[t.attr]}>')\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n elif t.value.id in self._locals:\n self.write(f'{t.value.id}.{t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifier not supported\")\n elif isinstance(t.value, ast.Call):\n self.dispatchMemberFunction(t.value.func, t.value)\n if t.value.call_type != 'MacroEnvironment':\n self.RaiseError(t, f'Function call {t.attr} is not supported')\n if not t.attr in self.fgpu_env_macro_funcs:\n self.RaiseError(t,\n f'Function {t.attr} is not a valid macro environment function'\n )\n self.write('(')\n self._CallArguments(t.value)\n self.write(')')\n self.write(f'.{t.attr}')\n else:\n self.RaiseError(t, 'Unsupported function call syntax')\n\n def _Module(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Interactive(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Expression(self, tree):\n self.dispatch(tree.body)\n\n def _Expr(self, tree):\n \"\"\"\n Same as a standard python expression but ends with semicolon\n \"\"\"\n if isinstance(tree.value, ast.Constant):\n if isinstance(tree.value.value, str):\n return\n elif isinstance(tree.value, ast.Str):\n return\n self.fill()\n self.dispatch(tree.value)\n self.write(';')\n\n def _NamedExpr(self, tree):\n \"\"\"\n No such concept in C++. Standard assignment can be used in any location.\n \"\"\"\n self.write('(')\n self.dispatch(tree.target)\n self.write(' = ')\n self.dispatch(tree.value)\n self.write(')')\n\n def _Import(self, t):\n self.RaiseError(t, 'Importing of modules not supported')\n\n def _ImportFrom(self, t):\n self.RaiseError(t, 'Importing of modules not supported')\n\n def _Assign(self, t):\n \"\"\"\n Assignment will use the auto type to define a variable at first use else will perform standard assignment.\n Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.\n Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.\n \"\"\"\n if len(t.targets) > 1:\n self.RaiseError(t, 'Assignment to multiple targets not supported')\n if not isinstance(t.targets[0], ast.Name):\n self.RaiseError(t,\n 'Assignment to complex expressions not supported')\n self.fill()\n if t.targets[0].id not in self._locals:\n self.write('auto ')\n self._locals.append(t.targets[0].id)\n self.dispatch(t.targets[0])\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n\n def _AugAssign(self, t):\n \"\"\"\n Similar to assignment in terms of restrictions. E.g. Allow only single named variable assignments.\n Also requires the named variable to already exist in scope.\n \"\"\"\n if not isinstance(t.target, ast.Name):\n self.RaiseError(t,\n 'Augmented assignment to complex expressions not supported')\n if t.target.id not in self._locals:\n self.RaiseError(t,\n 'Augmented assignment not permitted on variables not already assigned previously'\n )\n self.fill()\n self.dispatch(t.target)\n self.write(' ' + self.binop[t.op.__class__.__name__] + '= ')\n self.dispatch(t.value)\n self.write(';')\n\n def _AnnAssign(self, t):\n if not isinstance(t.target, ast.Name):\n self.RaiseError(t,\n 'Augmented assignment to complex expressions not supported')\n self.fill()\n self.dispatchType(t.annotation)\n self.write(' ')\n self.dispatch(t.target)\n if t.value:\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n <mask token>\n <mask token>\n\n def _Break(self, t):\n self.fill('break;')\n\n def _Continue(self, t):\n self.fill('continue;')\n\n def _Delete(self, t):\n self.RaiseError(t, 'Deletion not supported')\n\n def _Assert(self, t):\n \"\"\"\n cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy\n \"\"\"\n self.RaiseError(t, 'Assert not supported')\n\n def _Exec(self, t):\n self.RaiseError(t, 'Exec not supported')\n\n def _Print(self, t):\n \"\"\"\n This is old school python printing so no need to support\n \"\"\"\n self.RaiseError(t, 'Print not supported')\n\n def _Global(self, t):\n self.RaiseError(t, \"Use of 'global' not supported\")\n\n def _Nonlocal(self, t):\n self.RaiseError(t, \"Use of 'nonlocal' not supported\")\n <mask token>\n\n def _Yield(self, t):\n self.RaiseError(t, 'Yield not supported')\n\n def _YieldFrom(self, t):\n self.RaiseError(t, 'Yield from not supported')\n\n def _Raise(self, t):\n \"\"\"\n Exceptions are obviously supported in cpp but not in CUDA device code\n \"\"\"\n self.RaiseError(t, 'Exception raising not supported')\n\n def _Try(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _TryExcept(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _TryFinally(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _ExceptHandler(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _ClassDef(self, t):\n self.RaiseError(t, 'Class definitions not supported')\n\n def _FunctionDef(self, t):\n \"\"\"\n Checks the decorators of the function definition much must be either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'.\n Each is then processed in a different way using a specific dispatcher.\n Function calls are actually checked and only permitted (or user defined) function calls are supported.\n \"\"\"\n self.write('\\n')\n if len(t.decorator_list) != 1 or not isinstance(t.decorator_list[0],\n ast.Attribute):\n self.RaiseError(t,\n \"Function definitions require a single pyflamegpu decorator of either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'\"\n )\n if t.decorator_list[0].attr == 'agent_function' and t.decorator_list[0\n ].value.id == 'pyflamegpu':\n if getattr(t, 'returns', False):\n self.RaiseWarning(t,\n \"Function definition return type not supported on 'pyflamegpu.agent_function'\"\n )\n self.fill(f'FLAMEGPU_AGENT_FUNCTION({t.name}, ')\n self.dispatchFGPUFunctionArgs(t)\n self.write(')')\n elif t.decorator_list[0\n ].attr == 'device_function' and t.decorator_list[0\n ].value.id == 'pyflamegpu':\n self.fill(f'FLAMEGPU_DEVICE_FUNCTION ')\n if t.returns:\n self.dispatchType(t.returns)\n else:\n self.write('void')\n self.write(f' {t.name}(')\n self.dispatchFGPUDeviceFunctionArgs(t)\n self.write(')')\n self._device_functions.append(t.name)\n elif t.decorator_list[0\n ].attr == 'agent_function_condition' and t.decorator_list[0\n ].value.id == 'pyflamegpu':\n if not hasattr(t, 'returns'):\n self.RaiseError(t,\n \"Agent function conditions must have a 'bool' return type specified as a return type annotation\"\n )\n if not isinstance(t.returns, ast.Name):\n self.RaiseError(t,\n \"Agent function conditions return type must be 'bool'\")\n if t.returns.id is not 'bool':\n self.RaiseError(t,\n \"Agent function conditions return type must be 'bool'\")\n if t.args.args:\n self.RaiseWarning(t,\n 'Agent function conditions does not support arguments. These will be discarded.'\n )\n self.fill(f'FLAMEGPU_AGENT_FUNCTION_CONDITION({t.name})')\n else:\n self.RaiseError(t,\n \"Function definition uses an unsupported decorator. Must use either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'\"\n )\n self.enter()\n self.dispatch(t.body)\n self.leave()\n\n def _AsyncFunctionDef(self, t):\n self.RaiseError(t, 'Async functions not supported')\n\n def _For(self, t):\n \"\"\"\n Two type for for loop are supported. Either;\n 1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'\n 2) A range based for loop with 1 to 3 arguments which is converted into a c style loop\n \"\"\"\n if isinstance(t.iter, ast.Name):\n if t.iter.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration using 'message_in' iterator\"\n )\n elif t.orelse:\n self.RaiseError(t, 'For else not supported')\n elif isinstance(t.iter, ast.Call):\n if isinstance(t.iter.func, ast.Name):\n if t.iter.func.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n elif t.iter.func.id == 'range':\n if len(t.iter.args) == 1:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=0;')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 2:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 3:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('+=')\n self.dispatch(t.iter.args[2])\n self.write(')')\n else:\n self.RaiseError(t,\n \"Range based for loops requires use of 'range' function with arguments and not keywords\"\n )\n self.enter()\n self.dispatch(t.body)\n self.leave()\n else:\n self.RaiseError(t,\n \"Range based for loops only support calls to the 'range' function\"\n )\n elif isinstance(t.iter.func, ast.Attribute):\n if t.iter.func.value.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n 'Range based for loops only support calling members of message input variable'\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n\n def _AsyncFor(self, t):\n self.RaiseError(t, 'Async for not supported')\n\n def _If(self, t):\n \"\"\"\n Fairly straightforward translation to if, else if, else format\n \"\"\"\n self.fill('if (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0],\n ast.If):\n t = t.orelse[0]\n self.fill('else if (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.fill('else')\n self.enter()\n self.dispatch(t.orelse)\n self.leave()\n\n def _While(self, t):\n \"\"\"\n Straightforward translation to c style while loop\n \"\"\"\n self.fill('while (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.RaiseError(t, 'While else not supported')\n\n def _With(self, t):\n self.RaiseError(t, 'With not supported')\n\n def _AsyncWith(self, t):\n self.RaiseError(t, 'Async with not supported')\n\n def _Bytes(self, t):\n self.RaiseError(t, 'Byte strings and Bytes function not supported')\n <mask token>\n\n def _JoinedStr(self, t):\n self.RaiseError(t, 'Joined strings not supported')\n <mask token>\n\n def _fstring_JoinedStr(self, t, write):\n self.RaiseError(t, 'F strings not supported')\n <mask token>\n\n def _fstring_Constant(self, t, write):\n self.RaiseError(t, 'F strings not supported')\n\n def _fstring_FormattedValue(self, t, write):\n self.RaiseError(t, 'F strings not supported')\n\n def _Name(self, t):\n \"\"\"\n Everything ends up as a Name once it is an identifier\n \"\"\"\n self.write(t.id)\n\n def _NameConstant(self, t):\n if t.value == None:\n self.write(0)\n elif t.value:\n self.write('true')\n else:\n self.write('false')\n\n def _Repr(self, t):\n self.RaiseError(t, 'Repr not supported')\n\n def _Constant(self, t):\n \"\"\"\n Restrict most types of constant except for numeric types and constant strings\n Picks up some obvious conversions such as None and Bools\n \"\"\"\n value = t.value\n if isinstance(value, tuple):\n self.RaiseError(t, 'Tuples not supported')\n if isinstance(value, dict):\n self.RaiseError(t, 'Dictionaries not supported')\n if isinstance(value, list):\n self.RaiseError(t, 'Lists not supported')\n elif value is Ellipsis:\n self.RaiseError(t, 'Ellipsis not supported')\n elif isinstance(value, str):\n self.write(f'\"{value}\"')\n elif isinstance(value, (bytes, bytearray)):\n self.RaiseError(t, 'Byte strings and Bytes function not supported')\n elif isinstance(value, bool):\n if value:\n self.write('true')\n else:\n self.write('false')\n elif value == None:\n self.write(0)\n else:\n self.write(repr(value))\n\n def _Num(self, t):\n self.write(repr(t.n))\n\n def _List(self, t):\n self.RaiseError(t, 'Lists not supported')\n\n def _ListComp(self, t):\n self.RaiseError(t, 'List comprehension not supported')\n\n def _GeneratorExp(self, t):\n self.RaiseError(t, 'Generator expressions not supported')\n\n def _SetComp(self, t):\n self.RaiseError(t, 'Set comprehension not supported')\n\n def _DictComp(self, t):\n self.RaiseError(t, 'Dictionary comprehension not supported')\n\n def _comprehension(self, t):\n self.RaiseError(t, 'Comprehension not supported')\n\n def _IfExp(self, t):\n \"\"\"\n Equivalent to a ternary operator\n \"\"\"\n self.dispatch(t.test)\n self.write(' ? ')\n self.dispatch(t.body)\n self.write(' : ')\n self.dispatch(t.orelse)\n <mask token>\n\n def _Dict(self, t):\n self.RaiseError(t, 'Dictionaries not supported')\n\n def _Tuple(self, t):\n self.RaiseError(t, 'Tuples not supported')\n <mask token>\n <mask token>\n <mask token>\n\n def _BinOp(self, t):\n \"\"\"\n Python style pow and floordiv are not supported so translate to a function call.\n No matrix mul support.\n \"\"\"\n op_name = t.op.__class__.__name__\n if op_name == 'Pow':\n self.write('pow(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'FloorDiv':\n self.write('floor(')\n self.dispatch(t.left)\n self.write('/')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'MatMult':\n self.RaiseError(t, 'Matrix multiplier operator not supported')\n else:\n self.write('(')\n self.dispatch(t.left)\n self.write(' ' + self.binop[op_name] + ' ')\n self.dispatch(t.right)\n self.write(')')\n <mask token>\n\n def _Compare(self, t):\n self.dispatch(t.left)\n for o, e in zip(t.ops, t.comparators):\n if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':\n self.RaiseError(t, 'In and NotIn operators not supported')\n self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')\n self.dispatch(e)\n <mask token>\n <mask token>\n\n def _Attribute(self, t):\n \"\"\"\n A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.\n Attributes supported are only;\n * pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.\n * math.constant - Any supported math constants are translated to C definition versions\n \"\"\"\n func_dict = None\n if isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n if t.attr in self.fgpu_attrs:\n self.write('flamegpu::')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Attribute '{t.attr}' does not exist in pyflamegpu object\"\n )\n elif t.value.id == 'math':\n if t.attr in self.mathconsts:\n self.write(self.mathconsts[t.attr])\n else:\n self.RaiseError(t, f\"Unsupported math constant '{t.attr}'\")\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(self.numpytypes[t.attr])\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifiers not supported\")\n else:\n self.RaiseError(t, 'Unsupported attribute')\n\n def _CallArguments(self, t):\n comma = False\n for e in t.args:\n if comma:\n self.write(', ')\n else:\n comma = True\n self.dispatch(e)\n if len(t.keywords):\n self.RaiseWarning(t, 'Keyword argument not supported. Ignored.')\n if sys.version_info[:2] < (3, 5):\n if t.starargs:\n self.RaiseWarning(t, 'Starargs not supported. Ignored.')\n if t.kwargs:\n self.RaiseWarning(t, 'Kwargs not supported. Ignored.')\n <mask token>\n <mask token>\n\n def _Starred(self, t):\n self.RaiseError(t, 'Starred values not supported')\n\n def _Ellipsis(self, t):\n self.RaiseError(t, 'Ellipsis values not supported')\n\n def _Index(self, t):\n self.RaiseError(t, 'Index values not supported')\n\n def _Slice(self, t):\n self.RaiseError(t, 'Slicing values not supported')\n <mask token>\n\n def _arg(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, 'Arguments should already have been processed')\n\n def _arguments(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, 'Arguments should already have been processed')\n\n def _keyword(self, t):\n self.RaiseError(t, 'Keywords are not supported')\n\n def _Lambda(self, t):\n self.RaiseError(t, 'Lambda is not supported')\n\n def _alias(self, t):\n self.RaiseError(t, 'Aliasing is not supported')\n\n def _withitem(self, t):\n self.RaiseError(t, 'With not supported')\n",
"step-4": "<mask token>\n\n\nclass CodeGenerator:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, tree, file=sys.stdout):\n \"\"\"CodeGenerator(tree, file=sys.stdout) -> None.\n Print the source for tree to file.\"\"\"\n self.f = file\n self.future_imports = []\n self._indent = 0\n self._locals = ['pyflamegpu']\n self._device_functions = []\n self._message_iterator_var = None\n self._input_message_var = 'message_in'\n self._output_message_var = 'message_out'\n self.dispatch(tree)\n print('', file=self.f)\n self.f.flush()\n\n def _deviceVariableFunctionName(self, tree, permitted_prefixes,\n allow_lengths=True):\n \"\"\"\n Gets the device function name by translating a typed Python version to a templated cpp version.\n Python functions looks like getVariableFloatArray6 and translate to getVariable<float, 6>\n This function will detect and test against a set of known types and also extract the Array length\n This function returns None if the string is invalid in format but only throws an error if the format is correct but the type is invalid.\n \"\"\"\n cpp_func_name = ''\n py_func = tree.attr\n for prefix in permitted_prefixes:\n if py_func.startswith(prefix):\n cpp_func_name = prefix\n py_func = py_func[len(prefix):]\n break\n else:\n return None\n if allow_lengths:\n type_and_length = py_func.split('Array')\n if type_and_length[0] not in self._fgpu_types:\n self.RaiseError(tree,\n f\"'{type_and_length[0]}' is not a valid FLAME GPU type\")\n t = self._fgpu_types[type_and_length[0]]\n if len(type_and_length) == 1:\n cpp_func_name += f'<{t}>'\n elif len(type_and_length) == 2:\n cpp_func_name += f'<{t}, {type_and_length[1]}>'\n else:\n return None\n else:\n if py_func not in self._fgpu_types:\n self.RaiseError(tree,\n f\"'{py_func}' is not a valid FLAME GPU type\")\n t = self._fgpu_types[py_func]\n cpp_func_name += f'<{t}>'\n return cpp_func_name\n\n def fill(self, text=''):\n \"\"\"Indent a piece of text, according to the current indentation level\"\"\"\n self.f.write('\\n' + ' ' * self._indent + text)\n\n def write(self, text):\n \"\"\"Append a piece of text to the current line.\"\"\"\n self.f.write(str(text))\n\n def enter(self):\n \"\"\"Print '{', and increase the indentation.\"\"\"\n self.write('{')\n self._indent += 1\n\n def leave(self):\n \"\"\"Decrease the indentation level and Print '}'\"\"\"\n self._indent -= 1\n self.fill('}')\n\n def dispatch(self, tree):\n \"\"\"Dispatcher function, dispatching tree type T to method _T.\"\"\"\n if isinstance(tree, list):\n for t in tree:\n self.dispatch(t)\n return\n meth = getattr(self, '_' + tree.__class__.__name__)\n meth(tree)\n\n def RaiseWarning(self, tree, str):\n warnings.warn(f'Warning ({tree.lineno}, {tree.col_offset}): {str}')\n\n def RaiseError(self, tree, str):\n raise CodeGenException(\n f'Error ({tree.lineno}, {tree.col_offset}): {str}')\n\n def dispatchMacroEnvFunction(self, tree, tree_parent):\n \"\"\"\n Function will handle a getMacroEnvironment function (assuming it is correctly formatted (by checking with _deviceVariableFunctionName first))\n \"\"\"\n cpp_func_name = 'getMacroProperty'\n py_func = tree.attr\n py_type = py_func[len(cpp_func_name):]\n if py_type not in self._fgpu_types:\n self.RaiseError(tree, f\"'{py_type}' is not a valid FLAME GPU type\")\n t = self._fgpu_types[py_type]\n cpp_func_name += f'<{t}'\n if not tree_parent.args:\n self.RaiseError(tree,\n f\" Macro environment function '{py_func}' is expected to have some arguments.\"\n )\n if len(tree_parent.args) > 1:\n bounds = tree_parent.args[1:]\n for i in bounds:\n if isinstance(i, ast.Num):\n if not isinstance(i.n, int):\n self.RaiseError(tree,\n f\" Macro environment function argument '{i}' should be an integer value.\"\n )\n cpp_func_name += f', {i.n}'\n else:\n if not isinstance(i, ast.Constant):\n self.RaiseError(tree,\n f\" Macro environment function argument '{i}' should be an constant value (or Num in Python <3.8).\"\n )\n if not isinstance(i.value, int):\n self.RaiseError(tree,\n f\" Macro environment function argument '{i}' should be an integer value.\"\n )\n cpp_func_name += f', {i.value}'\n del tree_parent.args[1:]\n cpp_func_name += '>'\n self.write(cpp_func_name)\n\n def dispatchFGPUFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`\n Type hinting is required to translate a type into a FLAME GPU Message type implementation\n \"\"\"\n self._locals = ['pyflamegpu']\n if len(tree.args.args) != 2:\n self.RaiseError(tree,\n 'Expected two FLAME GPU function arguments (input message and output message)'\n )\n if not tree.args.args[0].annotation:\n self.RaiseError(tree.args.args[0],\n 'Message input requires a supported type annotation')\n if not isinstance(tree.args.args[0].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[0].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[0],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n input_message_attr = tree.args.args[0\n ].annotation.value.id + '.' + tree.args.args[0].annotation.attr\n if input_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[0],\n 'Message input type annotation not a supported message type')\n self._input_message_var = tree.args.args[0].arg\n self.write(f'flamegpu::{tree.args.args[0].annotation.attr}')\n self.write(', ')\n if not tree.args.args[1].annotation:\n self.RaiseError(tree.args.args[1],\n 'Message output requires a supported type annotation')\n if not isinstance(tree.args.args[1].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n if not isinstance(tree.args.args[1].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation should be an attribute of the form pyflamegpu.MessageType'\n )\n output_message_attr = tree.args.args[1\n ].annotation.value.id + '.' + tree.args.args[1].annotation.attr\n if output_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[1],\n 'Message output type annotation not a supported message type')\n self._output_message_var = tree.args.args[1].arg\n self.write(f'flamegpu::{tree.args.args[1].annotation.attr}')\n\n def dispatchType(self, tree):\n \"\"\"\n There is a limited set of types and formats of type description supported. Types can be either;\n 1) A python built in type of int or float, or\n 2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16\n This function translates and a catches unsupported types but does not translate a function call (i.e. cast)\n \"\"\"\n if isinstance(tree, ast.Name):\n if tree.id not in self.basic_arg_types:\n self.RaiseError(tree, 'Not a supported type')\n self.write(tree.id)\n elif isinstance(tree, ast.Attribute):\n if not isinstance(tree.value, ast.Name):\n self.RaiseError(tree, 'Not a supported type')\n if not (tree.value.id == 'numpy' or tree.value.id == 'np'):\n self.RaiseError(tree, 'Not a supported type')\n if tree.attr not in self.numpytypes:\n self.RaiseError(tree, 'Not a supported numpy type')\n self.write(self.numpytypes[tree.attr])\n else:\n self.RaiseError(tree, 'Not a supported type')\n\n def dispatchFGPUDeviceFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU device function. Arguments must use type hinting to be translated to cpp.\n \"\"\"\n self._locals = ['pyflamegpu']\n first = True\n annotation = None\n for arg in tree.args.args:\n if not arg.annotation:\n self.RaiseError(arg,\n 'Device function argument requires type annotation')\n if not first:\n self.write(', ')\n self.dispatchType(arg.annotation)\n self.write(f' {arg.arg}')\n self._locals.append(arg.arg)\n first = False\n\n def dispatchMessageIteratorCall(self, tree):\n \"\"\"\n Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())\n Using this function avoid using the global call one which may accept member function calls to things that are not iterators.\n \"\"\"\n if isinstance(tree.func, ast.Name):\n self.write(f'FLAMEGPU->{tree.func.id}')\n if isinstance(tree.func, ast.Attribute):\n if isinstance(tree.func.value, ast.Name):\n if not tree.func.attr in self.fgpu_input_msg_iter_funcs:\n self.RaiseError(tree,\n f\"Message input loop iterator '{tree.func.attr}' is not supported.\"\n )\n self.write(f'FLAMEGPU->{tree.func.value.id}.{tree.func.attr}')\n else:\n self.RaiseError(tree,\n 'Message input loop iterator format incorrect.')\n self.write('(')\n self._CallArguments(tree)\n self.write(')')\n\n def dispatchMessageLoop(self, tree):\n \"\"\"\n This is a special case of a range based for loop in which iterator item returns a const referecne to the message.\n Any user specified message value can be used.\n \"\"\"\n self.fill('for (const auto& ')\n self.dispatch(tree.target)\n self.write(' : ')\n if isinstance(tree.iter, ast.Name):\n if not tree.iter.id == self._input_message_var:\n self.RaiseError(t,\n f\"Message input loop requires use of '{self._input_message_var}' as iterator.\"\n )\n self.write(f'FLAMEGPU->{self._input_message_var}')\n elif isinstance(tree.iter, ast.Call):\n self.dispatchMessageIteratorCall(tree.iter)\n else:\n self.RaiseError(tree,\n f'Message input loop iterator in unsupported format')\n self.write(')')\n self._message_iterator_var = tree.target.id\n self.enter()\n self.dispatch(tree.body)\n self.leave()\n self._message_iterator_var = None\n\n def dispatchMemberFunction(self, t, t_parent):\n \"\"\"\n A very limited set of function calls to members are supported so these are fully evaluated here.\n t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)\n Function calls permitted are;\n * pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.\n * message_input.function - a call to the message input variable (the name of which is specified in the function definition)\n * msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)\n * message_output.function - a call to the message output variable (the name of which is specified in the function definition)\n * pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.\n * math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`\n * numpy.type - Any numpy types are translated to static casts\n \"\"\"\n if not hasattr(t, 'value'):\n self.RaiseError(t, f'Function call is in an unsupported format.')\n if isinstance(t.value, ast.Attribute):\n t_parent.call_type = None\n if not isinstance(t.value.value, ast.Name):\n self.RaiseError(t, 'Unknown or unsupported nested attribute')\n if (t.value.value.id == 'pyflamegpu' and t.value.attr ==\n 'environment'):\n self.write('FLAMEGPU->environment.')\n if t.attr in self.fgpu_env_funcs:\n self.write(t.attr)\n elif t.attr.startswith('getProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getProperty'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment property function.\"\n )\n self.write(py_func)\n t_parent.call_type = 'Environment'\n elif t.attr.startswith('getMacroProperty'):\n py_func = self._deviceVariableFunctionName(t, [\n 'getMacroProperty'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function.\"\n )\n self.dispatchMacroEnvFunction(t, t_parent)\n t_parent.call_type = 'MacroEnvironment'\n else:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.environment object\"\n )\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'random':\n self.write('FLAMEGPU->random.')\n if t.attr in self.fgpu_rand_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'uniform', 'normal', 'logNormal'], allow_lengths=False)\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.random object\"\n )\n self.write(py_func)\n t_parent.call_type = 'Random'\n elif t.value.value.id == 'pyflamegpu' and t.value.attr == 'agent_out':\n self.write('FLAMEGPU->agent_out.')\n if t.attr in self.fgpu_agent_out_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu.agent_out object\"\n )\n self.write(py_func)\n t_parent.call_type = 'AgentOut'\n else:\n self.RaiseError(t,\n f'Unknown or unsupported nested attribute in {t.value.value.id}'\n )\n elif isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n self.write('FLAMEGPU->')\n if t.attr in self.fgpu_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable', 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in pyflamegpu object\"\n )\n self.write(py_func)\n elif t.value.id == self._input_message_var:\n if t.attr in self.fgpu_input_msg_funcs:\n self.write(f'FLAMEGPU->{self._input_message_var}.')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'\"\n )\n elif self._message_iterator_var and t.value.id == self._message_iterator_var:\n self.write(f'{self._message_iterator_var}.')\n if t.attr in self.fgpu_input_msg_iter_var_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'getVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object\"\n )\n self.write(py_func)\n elif t.value.id == self._output_message_var:\n self.write('FLAMEGPU->message_out.')\n if t.attr in self.fgpu_output_msg_funcs:\n self.write(t.attr)\n else:\n py_func = self._deviceVariableFunctionName(t, [\n 'setVariable'])\n if not py_func:\n self.RaiseError(t,\n f\"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object\"\n )\n self.write(py_func)\n elif t.value.id == 'math':\n self.write(t.attr)\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(f'static_cast<{self.numpytypes[t.attr]}>')\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n elif t.value.id in self._locals:\n self.write(f'{t.value.id}.{t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifier not supported\")\n elif isinstance(t.value, ast.Call):\n self.dispatchMemberFunction(t.value.func, t.value)\n if t.value.call_type != 'MacroEnvironment':\n self.RaiseError(t, f'Function call {t.attr} is not supported')\n if not t.attr in self.fgpu_env_macro_funcs:\n self.RaiseError(t,\n f'Function {t.attr} is not a valid macro environment function'\n )\n self.write('(')\n self._CallArguments(t.value)\n self.write(')')\n self.write(f'.{t.attr}')\n else:\n self.RaiseError(t, 'Unsupported function call syntax')\n\n def _Module(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Interactive(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Expression(self, tree):\n self.dispatch(tree.body)\n\n def _Expr(self, tree):\n \"\"\"\n Same as a standard python expression but ends with semicolon\n \"\"\"\n if isinstance(tree.value, ast.Constant):\n if isinstance(tree.value.value, str):\n return\n elif isinstance(tree.value, ast.Str):\n return\n self.fill()\n self.dispatch(tree.value)\n self.write(';')\n\n def _NamedExpr(self, tree):\n \"\"\"\n No such concept in C++. Standard assignment can be used in any location.\n \"\"\"\n self.write('(')\n self.dispatch(tree.target)\n self.write(' = ')\n self.dispatch(tree.value)\n self.write(')')\n\n def _Import(self, t):\n self.RaiseError(t, 'Importing of modules not supported')\n\n def _ImportFrom(self, t):\n self.RaiseError(t, 'Importing of modules not supported')\n\n def _Assign(self, t):\n \"\"\"\n Assignment will use the auto type to define a variable at first use else will perform standard assignment.\n Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.\n Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.\n \"\"\"\n if len(t.targets) > 1:\n self.RaiseError(t, 'Assignment to multiple targets not supported')\n if not isinstance(t.targets[0], ast.Name):\n self.RaiseError(t,\n 'Assignment to complex expressions not supported')\n self.fill()\n if t.targets[0].id not in self._locals:\n self.write('auto ')\n self._locals.append(t.targets[0].id)\n self.dispatch(t.targets[0])\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n\n def _AugAssign(self, t):\n \"\"\"\n Similar to assignment in terms of restrictions. E.g. Allow only single named variable assignments.\n Also requires the named variable to already exist in scope.\n \"\"\"\n if not isinstance(t.target, ast.Name):\n self.RaiseError(t,\n 'Augmented assignment to complex expressions not supported')\n if t.target.id not in self._locals:\n self.RaiseError(t,\n 'Augmented assignment not permitted on variables not already assigned previously'\n )\n self.fill()\n self.dispatch(t.target)\n self.write(' ' + self.binop[t.op.__class__.__name__] + '= ')\n self.dispatch(t.value)\n self.write(';')\n\n def _AnnAssign(self, t):\n if not isinstance(t.target, ast.Name):\n self.RaiseError(t,\n 'Augmented assignment to complex expressions not supported')\n self.fill()\n self.dispatchType(t.annotation)\n self.write(' ')\n self.dispatch(t.target)\n if t.value:\n self.write(' = ')\n self.dispatch(t.value)\n self.write(';')\n\n def _Return(self, t):\n \"\"\"\n Standard cpp like return with semicolon.\n \"\"\"\n self.fill('return')\n if t.value:\n self.write(' ')\n self.dispatch(t.value)\n self.write(';')\n\n def _Pass(self, t):\n self.fill(';')\n\n def _Break(self, t):\n self.fill('break;')\n\n def _Continue(self, t):\n self.fill('continue;')\n\n def _Delete(self, t):\n self.RaiseError(t, 'Deletion not supported')\n\n def _Assert(self, t):\n \"\"\"\n cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy\n \"\"\"\n self.RaiseError(t, 'Assert not supported')\n\n def _Exec(self, t):\n self.RaiseError(t, 'Exec not supported')\n\n def _Print(self, t):\n \"\"\"\n This is old school python printing so no need to support\n \"\"\"\n self.RaiseError(t, 'Print not supported')\n\n def _Global(self, t):\n self.RaiseError(t, \"Use of 'global' not supported\")\n\n def _Nonlocal(self, t):\n self.RaiseError(t, \"Use of 'nonlocal' not supported\")\n\n def _Await(self, t):\n self.RaiseError(t, 'Await not supported')\n\n def _Yield(self, t):\n self.RaiseError(t, 'Yield not supported')\n\n def _YieldFrom(self, t):\n self.RaiseError(t, 'Yield from not supported')\n\n def _Raise(self, t):\n \"\"\"\n Exceptions are obviously supported in cpp but not in CUDA device code\n \"\"\"\n self.RaiseError(t, 'Exception raising not supported')\n\n def _Try(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _TryExcept(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _TryFinally(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _ExceptHandler(self, t):\n self.RaiseError(t, 'Exceptions not supported')\n\n def _ClassDef(self, t):\n self.RaiseError(t, 'Class definitions not supported')\n\n def _FunctionDef(self, t):\n \"\"\"\n Checks the decorators of the function definition much must be either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'.\n Each is then processed in a different way using a specific dispatcher.\n Function calls are actually checked and only permitted (or user defined) function calls are supported.\n \"\"\"\n self.write('\\n')\n if len(t.decorator_list) != 1 or not isinstance(t.decorator_list[0],\n ast.Attribute):\n self.RaiseError(t,\n \"Function definitions require a single pyflamegpu decorator of either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'\"\n )\n if t.decorator_list[0].attr == 'agent_function' and t.decorator_list[0\n ].value.id == 'pyflamegpu':\n if getattr(t, 'returns', False):\n self.RaiseWarning(t,\n \"Function definition return type not supported on 'pyflamegpu.agent_function'\"\n )\n self.fill(f'FLAMEGPU_AGENT_FUNCTION({t.name}, ')\n self.dispatchFGPUFunctionArgs(t)\n self.write(')')\n elif t.decorator_list[0\n ].attr == 'device_function' and t.decorator_list[0\n ].value.id == 'pyflamegpu':\n self.fill(f'FLAMEGPU_DEVICE_FUNCTION ')\n if t.returns:\n self.dispatchType(t.returns)\n else:\n self.write('void')\n self.write(f' {t.name}(')\n self.dispatchFGPUDeviceFunctionArgs(t)\n self.write(')')\n self._device_functions.append(t.name)\n elif t.decorator_list[0\n ].attr == 'agent_function_condition' and t.decorator_list[0\n ].value.id == 'pyflamegpu':\n if not hasattr(t, 'returns'):\n self.RaiseError(t,\n \"Agent function conditions must have a 'bool' return type specified as a return type annotation\"\n )\n if not isinstance(t.returns, ast.Name):\n self.RaiseError(t,\n \"Agent function conditions return type must be 'bool'\")\n if t.returns.id is not 'bool':\n self.RaiseError(t,\n \"Agent function conditions return type must be 'bool'\")\n if t.args.args:\n self.RaiseWarning(t,\n 'Agent function conditions does not support arguments. These will be discarded.'\n )\n self.fill(f'FLAMEGPU_AGENT_FUNCTION_CONDITION({t.name})')\n else:\n self.RaiseError(t,\n \"Function definition uses an unsupported decorator. Must use either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'\"\n )\n self.enter()\n self.dispatch(t.body)\n self.leave()\n\n def _AsyncFunctionDef(self, t):\n self.RaiseError(t, 'Async functions not supported')\n\n def _For(self, t):\n \"\"\"\n Two type for for loop are supported. Either;\n 1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'\n 2) A range based for loop with 1 to 3 arguments which is converted into a c style loop\n \"\"\"\n if isinstance(t.iter, ast.Name):\n if t.iter.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration using 'message_in' iterator\"\n )\n elif t.orelse:\n self.RaiseError(t, 'For else not supported')\n elif isinstance(t.iter, ast.Call):\n if isinstance(t.iter.func, ast.Name):\n if t.iter.func.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n elif t.iter.func.id == 'range':\n if len(t.iter.args) == 1:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=0;')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 2:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('++)')\n elif len(t.iter.args) == 3:\n self.fill(f'for (int ')\n self.dispatch(t.target)\n self.write('=')\n self.dispatch(t.iter.args[0])\n self.write(';')\n self.dispatch(t.target)\n self.write('<')\n self.dispatch(t.iter.args[1])\n self.write(';')\n self.dispatch(t.target)\n self.write('+=')\n self.dispatch(t.iter.args[2])\n self.write(')')\n else:\n self.RaiseError(t,\n \"Range based for loops requires use of 'range' function with arguments and not keywords\"\n )\n self.enter()\n self.dispatch(t.body)\n self.leave()\n else:\n self.RaiseError(t,\n \"Range based for loops only support calls to the 'range' function\"\n )\n elif isinstance(t.iter.func, ast.Attribute):\n if t.iter.func.value.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t,\n 'Range based for loops only support calling members of message input variable'\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n else:\n self.RaiseError(t,\n \"Range based for loops only support message iteration or use of 'range'\"\n )\n\n def _AsyncFor(self, t):\n self.RaiseError(t, 'Async for not supported')\n\n def _If(self, t):\n \"\"\"\n Fairly straightforward translation to if, else if, else format\n \"\"\"\n self.fill('if (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n while t.orelse and len(t.orelse) == 1 and isinstance(t.orelse[0],\n ast.If):\n t = t.orelse[0]\n self.fill('else if (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.fill('else')\n self.enter()\n self.dispatch(t.orelse)\n self.leave()\n\n def _While(self, t):\n \"\"\"\n Straightforward translation to c style while loop\n \"\"\"\n self.fill('while (')\n self.dispatch(t.test)\n self.write(')')\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.RaiseError(t, 'While else not supported')\n\n def _With(self, t):\n self.RaiseError(t, 'With not supported')\n\n def _AsyncWith(self, t):\n self.RaiseError(t, 'Async with not supported')\n\n def _Bytes(self, t):\n self.RaiseError(t, 'Byte strings and Bytes function not supported')\n\n def _Str(self, tree):\n self.write(f'\"{tree.s}\"')\n\n def _JoinedStr(self, t):\n self.RaiseError(t, 'Joined strings not supported')\n <mask token>\n\n def _fstring_JoinedStr(self, t, write):\n self.RaiseError(t, 'F strings not supported')\n <mask token>\n\n def _fstring_Constant(self, t, write):\n self.RaiseError(t, 'F strings not supported')\n\n def _fstring_FormattedValue(self, t, write):\n self.RaiseError(t, 'F strings not supported')\n\n def _Name(self, t):\n \"\"\"\n Everything ends up as a Name once it is an identifier\n \"\"\"\n self.write(t.id)\n\n def _NameConstant(self, t):\n if t.value == None:\n self.write(0)\n elif t.value:\n self.write('true')\n else:\n self.write('false')\n\n def _Repr(self, t):\n self.RaiseError(t, 'Repr not supported')\n\n def _Constant(self, t):\n \"\"\"\n Restrict most types of constant except for numeric types and constant strings\n Picks up some obvious conversions such as None and Bools\n \"\"\"\n value = t.value\n if isinstance(value, tuple):\n self.RaiseError(t, 'Tuples not supported')\n if isinstance(value, dict):\n self.RaiseError(t, 'Dictionaries not supported')\n if isinstance(value, list):\n self.RaiseError(t, 'Lists not supported')\n elif value is Ellipsis:\n self.RaiseError(t, 'Ellipsis not supported')\n elif isinstance(value, str):\n self.write(f'\"{value}\"')\n elif isinstance(value, (bytes, bytearray)):\n self.RaiseError(t, 'Byte strings and Bytes function not supported')\n elif isinstance(value, bool):\n if value:\n self.write('true')\n else:\n self.write('false')\n elif value == None:\n self.write(0)\n else:\n self.write(repr(value))\n\n def _Num(self, t):\n self.write(repr(t.n))\n\n def _List(self, t):\n self.RaiseError(t, 'Lists not supported')\n\n def _ListComp(self, t):\n self.RaiseError(t, 'List comprehension not supported')\n\n def _GeneratorExp(self, t):\n self.RaiseError(t, 'Generator expressions not supported')\n\n def _SetComp(self, t):\n self.RaiseError(t, 'Set comprehension not supported')\n\n def _DictComp(self, t):\n self.RaiseError(t, 'Dictionary comprehension not supported')\n\n def _comprehension(self, t):\n self.RaiseError(t, 'Comprehension not supported')\n\n def _IfExp(self, t):\n \"\"\"\n Equivalent to a ternary operator\n \"\"\"\n self.dispatch(t.test)\n self.write(' ? ')\n self.dispatch(t.body)\n self.write(' : ')\n self.dispatch(t.orelse)\n\n def _Set(self, t):\n self.RaiseError(t, 'Sets not supported')\n\n def _Dict(self, t):\n self.RaiseError(t, 'Dictionaries not supported')\n\n def _Tuple(self, t):\n self.RaiseError(t, 'Tuples not supported')\n <mask token>\n\n def _UnaryOp(self, t):\n \"\"\"\n Translate to C equivalent opertaors\n \"\"\"\n self.write('(')\n self.write(self.unop[t.op.__class__.__name__])\n self.dispatch(t.operand)\n self.write(')')\n <mask token>\n\n def _BinOp(self, t):\n \"\"\"\n Python style pow and floordiv are not supported so translate to a function call.\n No matrix mul support.\n \"\"\"\n op_name = t.op.__class__.__name__\n if op_name == 'Pow':\n self.write('pow(')\n self.dispatch(t.left)\n self.write(', ')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'FloorDiv':\n self.write('floor(')\n self.dispatch(t.left)\n self.write('/')\n self.dispatch(t.right)\n self.write(')')\n elif op_name == 'MatMult':\n self.RaiseError(t, 'Matrix multiplier operator not supported')\n else:\n self.write('(')\n self.dispatch(t.left)\n self.write(' ' + self.binop[op_name] + ' ')\n self.dispatch(t.right)\n self.write(')')\n <mask token>\n\n def _Compare(self, t):\n self.dispatch(t.left)\n for o, e in zip(t.ops, t.comparators):\n if o.__class__.__name__ == 'In' or o.__class__.__name__ == 'NotIn':\n self.RaiseError(t, 'In and NotIn operators not supported')\n self.write(' ' + self.cmpops[o.__class__.__name__] + ' ')\n self.dispatch(e)\n <mask token>\n\n def _BoolOp(self, t):\n \"\"\"\n Translate to logical and/or operators in C\n \"\"\"\n self.write('(')\n s = ' %s ' % self.boolops[t.op.__class__]\n interleave(lambda : self.write(s), self.dispatch, t.values)\n self.write(')')\n\n def _Attribute(self, t):\n \"\"\"\n A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.\n Attributes supported are only;\n * pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.\n * math.constant - Any supported math constants are translated to C definition versions\n \"\"\"\n func_dict = None\n if isinstance(t.value, ast.Name):\n if t.value.id == 'pyflamegpu':\n if t.attr in self.fgpu_attrs:\n self.write('flamegpu::')\n self.write(t.attr)\n else:\n self.RaiseError(t,\n f\"Attribute '{t.attr}' does not exist in pyflamegpu object\"\n )\n elif t.value.id == 'math':\n if t.attr in self.mathconsts:\n self.write(self.mathconsts[t.attr])\n else:\n self.RaiseError(t, f\"Unsupported math constant '{t.attr}'\")\n elif t.value.id == 'numpy' or t.value.id == 'np':\n if t.attr in self.numpytypes:\n self.write(self.numpytypes[t.attr])\n else:\n self.RaiseError(t, f'Unsupported numpy type {t.attr}')\n else:\n self.RaiseError(t,\n f\"Global '{t.value.id}' identifiers not supported\")\n else:\n self.RaiseError(t, 'Unsupported attribute')\n\n def _CallArguments(self, t):\n comma = False\n for e in t.args:\n if comma:\n self.write(', ')\n else:\n comma = True\n self.dispatch(e)\n if len(t.keywords):\n self.RaiseWarning(t, 'Keyword argument not supported. Ignored.')\n if sys.version_info[:2] < (3, 5):\n if t.starargs:\n self.RaiseWarning(t, 'Starargs not supported. Ignored.')\n if t.kwargs:\n self.RaiseWarning(t, 'Kwargs not supported. Ignored.')\n\n def _Call(self, t):\n \"\"\"\n Some basic checks are undertaken on calls to ensure that the function being called is either a builtin or defined device function.\n A special dispatcher is required \n \"\"\"\n funcs = self._device_functions + self.pythonbuiltins + [self.\n _input_message_var]\n if isinstance(t.func, ast.Name):\n if t.func.id not in funcs:\n self.RaiseWarning(t,\n 'Function call is not a defined FLAME GPU device function or a supported python built in.'\n )\n self.dispatch(t.func)\n elif isinstance(t.func, ast.Lambda):\n self.dispatch(t.func)\n else:\n self.dispatchMemberFunction(t.func, t)\n self.write('(')\n self._CallArguments(t)\n self.write(')')\n\n def _Subscript(self, t):\n \"\"\"\n Arrays are not supported but subscript allows accessing array like variables which is required for macro environment properties (e.g. a[0][1][2])\n Obvious limitation is no slicing type syntax (e.g. a[:2])\n \"\"\"\n self.dispatch(t.value)\n self.write('[')\n self.dispatch(t.slice)\n self.write(']')\n\n def _Starred(self, t):\n self.RaiseError(t, 'Starred values not supported')\n\n def _Ellipsis(self, t):\n self.RaiseError(t, 'Ellipsis values not supported')\n\n def _Index(self, t):\n self.RaiseError(t, 'Index values not supported')\n\n def _Slice(self, t):\n self.RaiseError(t, 'Slicing values not supported')\n\n def _ExtSlice(self, t):\n self.RaiseError(t, 'ExtSlice values not supported')\n\n def _arg(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, 'Arguments should already have been processed')\n\n def _arguments(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, 'Arguments should already have been processed')\n\n def _keyword(self, t):\n self.RaiseError(t, 'Keywords are not supported')\n\n def _Lambda(self, t):\n self.RaiseError(t, 'Lambda is not supported')\n\n def _alias(self, t):\n self.RaiseError(t, 'Aliasing is not supported')\n\n def _withitem(self, t):\n self.RaiseError(t, 'With not supported')\n",
"step-5": "from __future__ import print_function, unicode_literals\nimport sys\nimport ast\nimport os\nimport tokenize\nimport warnings\nfrom io import StringIO\n\ndef interleave(inter, f, seq):\n \"\"\"Call f on each item in seq, calling inter() in between.\n \"\"\"\n seq = iter(seq)\n try:\n f(next(seq))\n except StopIteration:\n pass\n else:\n for x in seq:\n inter()\n f(x)\n\nclass CodeGenException(Exception):\n \"\"\" Generic exception for errors raised in code generation \"\"\"\n pass\n\nclass CodeGenerator:\n \"\"\"Methods in this class recursively traverse an AST and\n output source code for the abstract syntax; original formatting\n is disregarded. \"\"\"\n\n # represents built in functions\n pythonbuiltins = [\"abs\", \"float\", \"int\"]\n \n # basic types\n basic_arg_types = ['float', 'int']\n \n # supported math constansts \n mathconsts = {\"pi\": \"M_PI\",\n \"e\": \"M_E\",\n \"inf\": \"INFINITY\",\n \"nan\": \"NAN\",\n }\n \n # support for most numpy types except complex numbers and float>64bit\n numpytypes = {\"byte\": \"char\",\n \"ubyte\": \"unsigned char\",\n \"short\": \"short\",\n \"ushort\": \"unsigned short\",\n \"intc\": \"int\",\n \"uintc\": \"unsigned int\",\n \"uint\": \"unisgned int\",\n \"longlong\": \"long long\",\n \"ulonglong\": \"unsigned long long\",\n \"half\": \"half\", # cuda supported \n \"single\": \"float\",\n \"double\": \"double\",\n \"longdouble\": \"long double\",\n \"bool_\": \"bool\",\n \"bool8\": \"bool\",\n # sized aliases\n \"int_\": \"long\",\n \"int8\": \"int8_t\",\n \"int16\": \"int16_t\",\n \"int32\": \"int32_t\",\n \"int64\": \"int64_t\",\n \"intp\": \"intptr_t\",\n \"uint_\": \"long\",\n \"uint8\": \"uint8_t\",\n \"uint16\": \"uint16_t\",\n \"uint32\": \"uint32_t\",\n \"uint64\": \"uint64_t\",\n \"uintp\": \"uintptr_t\",\n \"float_\": \"float\",\n \"float16\": \"half\",\n \"float32\": \"float\",\n \"float64\": \"double\"\n }\n \n # getVariableType and setVariableType functions are added dynamically \n fgpu_funcs = [ \"getID\", \"getStepCounter\", \"getIndex\" ] \n fgpu_attrs = [\"ALIVE\", \"DEAD\"]\n fgpu_input_msg_funcs = [\"radius\", \"at\"] # functions that can be called on message_in that do NOT return iterators\n fgpu_input_msg_iter_funcs = [\"wrap\", \"vn\", \"vn_wrap\"] # functions that can be called on message_in that do return iterators\n fgpu_input_msg_iter_var_funcs = [\"getIndex\", \"getVirtualX\", \"getVirtualY\", \"getVirtualZ\"] \n fgpu_output_msg_funcs = [\"setLocation\", \"setKey\", \"setIndex\"]\n fgpu_agent_out_msg_funcs = [\"getID\"]\n fgpu_env_funcs = [\"containsProperty\", \"containsMacroProperty\"]\n fgpu_env_macro_funcs = [\"exchange\", \"CAS\", \"min\", \"max\"]\n fgpu_rand_funcs = []\n fgpu_message_types = [\"pyflamegpu.MessageNone\", \"pyflamegpu.MessageBruteForce\", \"pyflamegpu.MessageBucket\", \"pyflamegpu.MessageSpatial2D\", \"pyflamegpu.MessageSpatial3D\", \"pyflamegpu.MessageArray\", \"pyflamegpu.MessageArray2D\", \"pyflamegpu.MessageArray3D\"]\n \n _fgpu_types = {\"Float\": \"float\",\n \"Double\": \"double\",\n \"Int\": \"int\",\n \"UInt\": \"unsigned int\",\n \"Int8\": \"int_8\",\n \"UInt8\": \"uint_8\",\n \"Char\": \"char\",\n \"UChar\": \"unsigned char\",\n \"Int16\": \"int_16\",\n \"UInt16\": \"uint_16\",\n \"Int32\": \"int_32\",\n \"UInt32\": \"uint_32\",\n \"Int64\": \"int_64\",\n \"UInt64\": \"uint_64\"\n }\n\n\n def __init__(self, tree, file = sys.stdout):\n \"\"\"CodeGenerator(tree, file=sys.stdout) -> None.\n Print the source for tree to file.\"\"\"\n self.f = file\n self.future_imports = []\n self._indent = 0\n # dict of locals used to determine if variable already exists in assignments\n self._locals = [\"pyflamegpu\"]\n self._device_functions = []\n self._message_iterator_var = None # default\n self._input_message_var = 'message_in' # default\n self._output_message_var = 'message_out' # default\n self.dispatch(tree)\n print(\"\", file=self.f)\n self.f.flush()\n \n \n def _deviceVariableFunctionName(self, tree, permitted_prefixes, allow_lengths = True):\n \"\"\"\n Gets the device function name by translating a typed Python version to a templated cpp version.\n Python functions looks like getVariableFloatArray6 and translate to getVariable<float, 6>\n This function will detect and test against a set of known types and also extract the Array length\n This function returns None if the string is invalid in format but only throws an error if the format is correct but the type is invalid.\n \"\"\"\n cpp_func_name = \"\"\n py_func = tree.attr\n # extract function name start\n for prefix in permitted_prefixes:\n if py_func.startswith(prefix):\n cpp_func_name = prefix\n py_func = py_func[len(prefix):]\n break # dont allow the else\n else:\n return None\n # check type and lengths\n if allow_lengths:\n #split to get type and Array Length (This could **potentially** be looked up from the model description but current syntax is consistent with swig bindings) \n type_and_length = py_func.split(\"Array\")\n if type_and_length[0] not in self._fgpu_types:\n self.RaiseError(tree, f\"'{type_and_length[0]}' is not a valid FLAME GPU type\")\n t = self._fgpu_types[type_and_length[0]]\n # generate template args\n if (len(type_and_length) == 1):\n cpp_func_name += f\"<{t}>\"\n elif (len(type_and_length) == 2):\n cpp_func_name += f\"<{t}, {type_and_length[1]}>\"\n else:\n return None\n else:\n if py_func not in self._fgpu_types:\n self.RaiseError(tree, f\"'{py_func}' is not a valid FLAME GPU type\")\n t = self._fgpu_types[py_func]\n cpp_func_name += f\"<{t}>\"\n # return \n return cpp_func_name\n \n\n def fill(self, text = \"\"):\n \"Indent a piece of text, according to the current indentation level\"\n self.f.write(\"\\n\"+\" \"*self._indent + text)\n\n def write(self, text):\n \"Append a piece of text to the current line.\"\n self.f.write(str(text))\n\n def enter(self):\n \"Print '{', and increase the indentation.\"\n self.write(\"{\")\n self._indent += 1\n\n def leave(self):\n \"Decrease the indentation level and Print '}'\"\n self._indent -= 1\n self.fill(\"}\")\n\n def dispatch(self, tree):\n \"Dispatcher function, dispatching tree type T to method _T.\"\n if isinstance(tree, list):\n for t in tree:\n self.dispatch(t)\n return\n meth = getattr(self, \"_\"+tree.__class__.__name__)\n meth(tree)\n \n def RaiseWarning(self, tree, str):\n warnings.warn(f\"Warning ({tree.lineno}, {tree.col_offset}): {str}\")\n \n def RaiseError(self, tree, str):\n raise CodeGenException(f\"Error ({tree.lineno}, {tree.col_offset}): {str}\")\n\n ############### Cutsom Unparsing methods ###############\n # These are special versions of the ast unparsing #\n # dispatch functions. #\n ########################################################\n \n def dispatchMacroEnvFunction(self, tree, tree_parent):\n \"\"\"\n Function will handle a getMacroEnvironment function (assuming it is correctly formatted (by checking with _deviceVariableFunctionName first))\n \"\"\"\n cpp_func_name = \"getMacroProperty\"\n py_func = tree.attr\n # extract type from function name\n py_type = py_func[len(cpp_func_name):]\n if py_type not in self._fgpu_types:\n self.RaiseError(tree, f\"'{py_type}' is not a valid FLAME GPU type\")\n # get cpp type\n t = self._fgpu_types[py_type]\n cpp_func_name += f\"<{t}\"\n # mess with the parent to extract (and remove arguments so they dont end up in the argument list)\n if not tree_parent.args :\n self.RaiseError(tree, f\" Macro environment function '{py_func}' is expected to have some arguments.\")\n # if more than one arg then the rest are bounds to translate\n if len(tree_parent.args) > 1:\n bounds = tree_parent.args[1:]\n # process bounds by appending to cpp function template arguments\n for i in bounds:\n if isinstance(i, ast.Num): # num required for python 3.7\n if not isinstance(i.n, int):\n self.RaiseError(tree, f\" Macro environment function argument '{i}' should be an integer value.\")\n cpp_func_name += f\", {i.n}\"\n else: # all Python > 3.7 \n if not isinstance(i, ast.Constant):\n self.RaiseError(tree, f\" Macro environment function argument '{i}' should be an constant value (or Num in Python <3.8).\")\n if not isinstance(i.value, int):\n self.RaiseError(tree, f\" Macro environment function argument '{i}' should be an integer value.\")\n cpp_func_name += f\", {i.value}\"\n # remove bounds from argument list (in place)\n del tree_parent.args[1:]\n cpp_func_name += \">\"\n self.write(cpp_func_name)\n\n def dispatchFGPUFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU function. Arguments must have syntax of `message_in: MessageInType, message_out: MessageOutType`\n Type hinting is required to translate a type into a FLAME GPU Message type implementation\n \"\"\"\n # reset the locals variable stack\n self._locals = [\"pyflamegpu\"]\n if len(tree.args.args) != 2:\n self.RaiseError(tree, \"Expected two FLAME GPU function arguments (input message and output message)\")\n # input message\n if not tree.args.args[0].annotation:\n self.RaiseError(tree.args.args[0], \"Message input requires a supported type annotation\")\n if not isinstance(tree.args.args[0].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[0], \"Message input type annotation should be an attribute of the form pyflamegpu.MessageType\")\n if not isinstance(tree.args.args[0].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[0], \"Message output type annotation should be an attribute of the form pyflamegpu.MessageType\")\n input_message_attr = tree.args.args[0].annotation.value.id + \".\" + tree.args.args[0].annotation.attr\n if input_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[0], \"Message input type annotation not a supported message type\")\n self._input_message_var = tree.args.args[0].arg # store the message input variable name\n self.write(f\"flamegpu::{tree.args.args[0].annotation.attr}\") # requires namespace\n self.write(\", \")\n # output message\n if not tree.args.args[1].annotation:\n self.RaiseError(tree.args.args[1], \"Message output requires a supported type annotation\")\n if not isinstance(tree.args.args[1].annotation, ast.Attribute):\n self.RaiseError(tree.args.args[1], \"Message output type annotation should be an attribute of the form pyflamegpu.MessageType\")\n if not isinstance(tree.args.args[1].annotation.value, ast.Name):\n self.RaiseError(tree.args.args[1], \"Message output type annotation should be an attribute of the form pyflamegpu.MessageType\")\n output_message_attr = tree.args.args[1].annotation.value.id + \".\" + tree.args.args[1].annotation.attr\n if output_message_attr not in self.fgpu_message_types:\n self.RaiseError(tree.args.args[1], \"Message output type annotation not a supported message type\")\n self._output_message_var = tree.args.args[1].arg # store the message output variable name\n self.write(f\"flamegpu::{tree.args.args[1].annotation.attr}\") # requires namespace\n \n def dispatchType(self, tree):\n \"\"\"\n There is a limited set of types and formats of type description supported. Types can be either;\n 1) A python built in type of int or float, or\n 2) A subset of numpy types prefixed with either numpy or np. e.g. np.int16\n This function translates and a catches unsupported types but does not translate a function call (i.e. cast)\n \"\"\"\n if isinstance(tree, ast.Name):\n if tree.id not in self.basic_arg_types:\n self.RaiseError(tree, \"Not a supported type\")\n self.write(tree.id)\n elif isinstance(tree, ast.Attribute):\n if not isinstance(tree.value, ast.Name) :\n self.RaiseError(tree, \"Not a supported type\")\n if not (tree.value.id == \"numpy\" or tree.value.id == \"np\"):\n self.RaiseError(tree, \"Not a supported type\")\n if tree.attr not in self.numpytypes:\n self.RaiseError(tree, \"Not a supported numpy type\")\n self.write(self.numpytypes[tree.attr])\n else:\n self.RaiseError(tree, \"Not a supported type\")\n \n def dispatchFGPUDeviceFunctionArgs(self, tree):\n \"\"\"\n Handles arguments for a FLAME GPU device function. Arguments must use type hinting to be translated to cpp.\n \"\"\"\n # reset the locals variable stack\n self._locals = [\"pyflamegpu\"]\n # input message\n first = True\n annotation = None\n for arg in tree.args.args:\n # ensure that there is a type annotation\n if not arg.annotation:\n self.RaiseError(arg, \"Device function argument requires type annotation\")\n # comma if not first\n if not first:\n self.write(\", \")\n self.dispatchType(arg.annotation)\n self.write(f\" {arg.arg}\")\n # add arg to local variable stack\n self._locals.append(arg.arg)\n first = False \n \n def dispatchMessageIteratorCall(self, tree):\n \"\"\"\n Message iterator call maybe a simple one (e.g. message_in(x, y, z)) or a call to a member (e.g. message_in.wrap())\n Using this function avoid using the global call one which may accept member function calls to things that are not iterators.\n \"\"\"\n # simple case not a member function just an iterator with arguments\n if isinstance(tree.func, ast.Name):\n self.write(f\"FLAMEGPU->{tree.func.id}\")\n if isinstance(tree.func, ast.Attribute) :\n if isinstance(tree.func.value, ast.Name):\n # check that the iterator is supported\n if not tree.func.attr in self.fgpu_input_msg_iter_funcs:\n self.RaiseError(tree, f\"Message input loop iterator '{tree.func.attr}' is not supported.\")\n self.write(f\"FLAMEGPU->{tree.func.value.id}.{tree.func.attr}\")\n else:\n self.RaiseError(tree, \"Message input loop iterator format incorrect.\")\n\n # handle function arguments \n self.write(\"(\")\n self._CallArguments(tree)\n self.write(\")\")\n\n def dispatchMessageLoop(self, tree):\n \"\"\"\n This is a special case of a range based for loop in which iterator item returns a const referecne to the message.\n Any user specified message value can be used.\n \"\"\"\n self.fill(\"for (const auto& \")\n self.dispatch(tree.target)\n self.write(\" : \")\n # if simple message iterator\n if isinstance(tree.iter, ast.Name):\n if not tree.iter.id == self._input_message_var:\n self.RaiseError(t, f\"Message input loop requires use of '{self._input_message_var}' as iterator.\")\n # write with prefix\n self.write(f\"FLAMEGPU->{self._input_message_var}\")\n # if it is a call then handle the different cases\n elif isinstance(tree.iter, ast.Call):\n self.dispatchMessageIteratorCall(tree.iter)\n #otherwise not supported\n else :\n self.RaiseError(tree, f\"Message input loop iterator in unsupported format\")\n self.write(\")\")\n self._message_iterator_var = tree.target.id\n self.enter()\n self.dispatch(tree.body)\n self.leave()\n self._message_iterator_var = None\n \n def dispatchMemberFunction(self, t, t_parent):\n \"\"\"\n A very limited set of function calls to members are supported so these are fully evaluated here.\n t_parent is the Call ast object required if the argument need to be modified (i.e. in the case of macro environment properties)\n Function calls permitted are;\n * pyflamegpu.function - a supported function call. e.g. pyflamegpu.getVariableFloat(). This will be translated into a typed Cpp call.\n * message_input.function - a call to the message input variable (the name of which is specified in the function definition)\n * msg.function - a call to the message input iterator objection variable (the name of which is specified in the message function loop)\n * message_output.function - a call to the message output variable (the name of which is specified in the function definition)\n * pyflamegpu.environment.function - the only nested attribute type. This will be translated into a typed Cpp call.\n * math.function - Any function calls from python `math` are translated to calls raw function calls. E.g. `math.sin()` becomes `sin()`\n * numpy.type - Any numpy types are translated to static casts\n \"\"\"\n # it could be possible that the Call object has no value property e.g. a()()\n if not hasattr(t, \"value\"):\n self.RaiseError(t, f\"Function call is in an unsupported format.\")\n\n # Nested member functions (e.g. x.y.z())\n if isinstance(t.value, ast.Attribute):\n # store some information about the source of this function call in parent as this may be useful for validation in whatever has called this function\n t_parent.call_type = None\n # only nested attribute type is environment\n if not isinstance(t.value.value, ast.Name):\n self.RaiseError(t, \"Unknown or unsupported nested attribute\")\n # pyflamegpu.environment\n if t.value.value.id == \"pyflamegpu\" and t.value.attr == \"environment\":\n # check it is a supported environment function\n self.write(\"FLAMEGPU->environment.\")\n if t.attr in self.fgpu_env_funcs: \n # proceed\n self.write(t.attr)\n else: \n # simple getProperty type function\n if t.attr.startswith('getProperty') :\n # possible getter setter type function\n py_func = self._deviceVariableFunctionName(t, [\"getProperty\"])\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' is not a supported pyflamegpu.environment property function.\")\n # write the getProperty type function\n self.write(py_func)\n t_parent.call_type = \"Environment\"\n # need to catch case of getMacroProperty as arguments need to be translated into template parameters in cpp (and py_func can be ignored)\n elif t.attr.startswith(\"getMacroProperty\"):\n # possible getter setter type function (Note: getMacroProperty only supports a subset of types but type checking is not performed. This is best left to the compiler.)\n # no not permit lengths (e.g. Float4) as these will be passed as arguments\n py_func = self._deviceVariableFunctionName(t, [\"getMacroProperty\"], allow_lengths=False)\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' is not a supported pyflamegpu.environment macro property function.\")\n # handle case\n self.dispatchMacroEnvFunction(t, t_parent)\n t_parent.call_type = \"MacroEnvironment\"\n else:\n self.RaiseError(t, f\"Function '{t.attr}' does not exist in pyflamegpu.environment object\")\n \n # pyflamegpu.random\n elif t.value.value.id == \"pyflamegpu\" and t.value.attr == \"random\":\n # check it is a supported random function\n self.write(\"FLAMEGPU->random.\")\n if t.attr in self.fgpu_rand_funcs: \n # proceed\n self.write(t.attr)\n else: \n # possible getter setter type function\n py_func = self._deviceVariableFunctionName(t, [\"uniform\", \"normal\", \"logNormal\"], allow_lengths=False)\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' does not exist in pyflamegpu.random object\")\n # proceed\n self.write(py_func) \n t_parent.call_type = \"Random\"\n elif t.value.value.id == \"pyflamegpu\" and t.value.attr == \"agent_out\":\n # check it is a supported agent_out function\n self.write(\"FLAMEGPU->agent_out.\")\n if t.attr in self.fgpu_agent_out_msg_funcs: \n # proceed\n self.write(t.attr)\n else: \n # possible getter setter type function\n py_func = self._deviceVariableFunctionName(t, [\"setVariable\"])\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' does not exist in pyflamegpu.agent_out object\")\n # proceed\n self.write(py_func)\n t_parent.call_type = \"AgentOut\"\n else:\n self.RaiseError(t, f\"Unknown or unsupported nested attribute in {t.value.value.id}\")\n # Non nested member functions (e.g. x.y())\n elif isinstance(t.value, ast.Name):\n # pyflamegpu singleton\n if t.value.id == \"pyflamegpu\":\n # check for legit FGPU function calls \n self.write(\"FLAMEGPU->\")\n if t.attr in self.fgpu_funcs:\n # proceed\n self.write(t.attr)\n else:\n # possible getter setter type function\n py_func = self._deviceVariableFunctionName(t, [\"getVariable\", \"setVariable\"])\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' does not exist in pyflamegpu object\")\n # proceed\n self.write(py_func)\n\n # message_in function using whatever variable was named in function declaration (e.g radius)\n elif t.value.id == self._input_message_var:\n # only process functions on message_in that are not iterators\n if t.attr in self.fgpu_input_msg_funcs:\n self.write(f\"FLAMEGPU->{self._input_message_var}.\")\n self.write(t.attr) \n else:\n self.RaiseError(t, f\"Message input variable '{self._input_message_var}' does not have a supported function '{t.attr}'\") \n\n # message input iterator arg\n elif self._message_iterator_var and t.value.id == self._message_iterator_var:\n self.write(f\"{self._message_iterator_var}.\")\n # check for legit FGPU function calls and translate\n if t.attr in self.fgpu_input_msg_iter_var_funcs: \n # proceed\n self.write(t.attr)\n else:\n # possible getter setter type function\n py_func = self._deviceVariableFunctionName(t, [\"getVariable\"])\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' does not exist in '{self._message_iterator_var}' message input iterable object\")\n # proceed\n self.write(py_func)\n \n # message output arg\n elif t.value.id == self._output_message_var:\n # check for legit FGPU function calls and translate\n self.write(\"FLAMEGPU->message_out.\")\n if t.attr in self.fgpu_output_msg_funcs: \n # proceed\n self.write(t.attr)\n else:\n # possible getter setter type function\n py_func = self._deviceVariableFunctionName(t, [\"setVariable\"])\n if not py_func:\n self.RaiseError(t, f\"Function '{t.attr}' does not exist in '{self._output_message_var}' message output object\")\n # proceed\n self.write(py_func)\n \n \n \n # math functions (try them in raw function call format) or constants\n elif t.value.id == \"math\":\n self.write(t.attr)\n # numpy types\n elif t.value.id == \"numpy\" or t.value.id == \"np\":\n if t.attr in self.numpytypes:\n self.write(f\"static_cast<{self.numpytypes[t.attr]}>\")\n else: \n self.RaiseError(t, f\"Unsupported numpy type {t.attr}\")\n # allow any call on any locals (too many cases to enforce without type checking)\n elif t.value.id in self._locals:\n self.write(f\"{t.value.id}.{t.attr}\")\n else:\n self.RaiseError(t, f\"Global '{t.value.id}' identifier not supported\")\n # Call is a very nested situation which can occur only on macro environment properties. E.g. 'pyflamegpu.environment.getMacroPropertyInt('a').exchange(10)'\n elif isinstance(t.value, ast.Call):\n # handle the call by recursively calling this function to do the depth first execution of pyflamegpu.environment.getMacroPropertyInt('a')\n self.dispatchMemberFunction(t.value.func, t.value)\n # check that the handler was actually for macro environment \n if t.value.call_type != \"MacroEnvironment\" :\n self.RaiseError(t, f\"Function call {t.attr} is not supported\")\n # now append the outer call by making sure the thing been called is a valid macro env function\n if not t.attr in self.fgpu_env_macro_funcs:\n self.RaiseError(t, f\"Function {t.attr} is not a valid macro environment function\")\n # write inner call args\n self.write(\"(\")\n self._CallArguments(t.value)\n self.write(\")\")\n # write outer function (call args will be completed by _Call)\n self.write(f\".{t.attr}\")\n \n \n else:\n self.RaiseError(t, \"Unsupported function call syntax\")\n \n ############### Unparsing methods ######################\n # There should be one method per concrete grammar type #\n # Constructors should be grouped by sum type. Ideally, #\n # this would follow the order in the grammar, but #\n # currently doesn't. #\n ########################################################\n\n def _Module(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Interactive(self, tree):\n for stmt in tree.body:\n self.dispatch(stmt)\n\n def _Expression(self, tree):\n self.dispatch(tree.body)\n\n # stmt\n def _Expr(self, tree):\n \"\"\"\n Same as a standard python expression but ends with semicolon\n \"\"\"\n # Catch odd case of multi line strings and doc strings which are Expr with a Constant string type value\n if isinstance(tree.value, ast.Constant):\n if isinstance(tree.value.value, str):\n return\n # catch special case of Python 3.7 Where doc string is a Str and not a Constant\n elif isinstance(tree.value, ast.Str):\n return \n # otherwise treat like a normal expression\n self.fill()\n self.dispatch(tree.value)\n self.write(\";\")\n\n def _NamedExpr(self, tree):\n \"\"\"\n No such concept in C++. Standard assignment can be used in any location.\n \"\"\"\n self.write(\"(\")\n self.dispatch(tree.target)\n self.write(\" = \")\n self.dispatch(tree.value)\n self.write(\")\")\n\n def _Import(self, t):\n self.RaiseError(t, \"Importing of modules not supported\")\n\n def _ImportFrom(self, t):\n self.RaiseError(t, \"Importing of modules not supported\")\n\n def _Assign(self, t):\n \"\"\"\n Assignment will use the auto type to define a variable at first use else will perform standard assignment.\n Note: There is no ability to create `const` variables unless this is inferred from the assignment expression.\n Multiple assignment is supported by cpp but not in the translator neither is assignment to complex expressions which are valid python syntax.\n \"\"\"\n if len(t.targets) > 1:\n self.RaiseError(t, \"Assignment to multiple targets not supported\")\n if not isinstance(t.targets[0], ast.Name):\n self.RaiseError(t, \"Assignment to complex expressions not supported\")\n self.fill()\n # check if target exists in locals\n if t.targets[0].id not in self._locals :\n self.write(\"auto \")\n self._locals.append(t.targets[0].id)\n self.dispatch(t.targets[0])\n self.write(\" = \")\n self.dispatch(t.value)\n self.write(\";\")\n\n def _AugAssign(self, t):\n \"\"\"\n Similar to assignment in terms of restrictions. E.g. Allow only single named variable assignments.\n Also requires the named variable to already exist in scope.\n \"\"\"\n if not isinstance(t.target, ast.Name):\n self.RaiseError(t, \"Augmented assignment to complex expressions not supported\")\n # check if target exists in locals\n if t.target.id not in self._locals :\n self.RaiseError(t, \"Augmented assignment not permitted on variables not already assigned previously\")\n self.fill()\n self.dispatch(t.target)\n self.write(\" \"+self.binop[t.op.__class__.__name__]+\"= \")\n self.dispatch(t.value)\n self.write(\";\")\n\n def _AnnAssign(self, t):\n if not isinstance(t.target, ast.Name):\n self.RaiseError(t, \"Augmented assignment to complex expressions not supported\")\n self.fill()\n self.dispatchType(t.annotation)\n self.write(\" \")\n self.dispatch(t.target)\n if t.value:\n self.write(\" = \")\n self.dispatch(t.value)\n self.write(\";\")\n\n def _Return(self, t):\n \"\"\"\n Standard cpp like return with semicolon.\n \"\"\"\n self.fill(\"return\")\n if t.value:\n self.write(\" \")\n self.dispatch(t.value)\n self.write(\";\")\n\n def _Pass(self, t):\n self.fill(\";\")\n\n def _Break(self, t):\n self.fill(\"break;\")\n\n def _Continue(self, t):\n self.fill(\"continue;\")\n\n def _Delete(self, t):\n self.RaiseError(t, \"Deletion not supported\")\n\n def _Assert(self, t):\n \"\"\"\n cassert does exist but probably not required in FGPU functions and unclear if supported by jitfy\n \"\"\"\n self.RaiseError(t, \"Assert not supported\")\n\n def _Exec(self, t):\n self.RaiseError(t, \"Exec not supported\")\n\n def _Print(self, t):\n \"\"\"\n This is old school python printing so no need to support\n \"\"\"\n self.RaiseError(t, \"Print not supported\")\n \n def _Global(self, t):\n self.RaiseError(t, \"Use of 'global' not supported\")\n\n def _Nonlocal(self, t):\n self.RaiseError(t, \"Use of 'nonlocal' not supported\")\n\n def _Await(self, t):\n self.RaiseError(t, \"Await not supported\")\n\n def _Yield(self, t):\n self.RaiseError(t, \"Yield not supported\")\n\n def _YieldFrom(self, t):\n self.RaiseError(t, \"Yield from not supported\")\n\n def _Raise(self, t):\n \"\"\"\n Exceptions are obviously supported in cpp but not in CUDA device code\n \"\"\"\n self.RaiseError(t, \"Exception raising not supported\")\n\n def _Try(self, t):\n self.RaiseError(t, \"Exceptions not supported\")\n\n def _TryExcept(self, t):\n self.RaiseError(t, \"Exceptions not supported\")\n\n def _TryFinally(self, t): \n self.RaiseError(t, \"Exceptions not supported\")\n\n def _ExceptHandler(self, t):\n self.RaiseError(t, \"Exceptions not supported\")\n\n def _ClassDef(self, t):\n self.RaiseError(t, \"Class definitions not supported\")\n\n def _FunctionDef(self, t):\n \"\"\"\n Checks the decorators of the function definition much must be either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'.\n Each is then processed in a different way using a specific dispatcher.\n Function calls are actually checked and only permitted (or user defined) function calls are supported.\n \"\"\"\n self.write(\"\\n\")\n # check decorators\n if len(t.decorator_list) != 1 or not isinstance(t.decorator_list[0], ast.Attribute):\n self.RaiseError(t, \"Function definitions require a single pyflamegpu decorator of either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'\") \n # FLAMEGPU_AGENT_FUNCTION\n if t.decorator_list[0].attr == 'agent_function' and t.decorator_list[0].value.id == 'pyflamegpu':\n if getattr(t, \"returns\", False):\n self.RaiseWarning(t, \"Function definition return type not supported on 'pyflamegpu.agent_function'\")\n self.fill(f\"FLAMEGPU_AGENT_FUNCTION({t.name}, \")\n self.dispatchFGPUFunctionArgs(t)\n self.write(\")\")\n # FLAMEGPU_DEVICE_FUNCTION\n elif t.decorator_list[0].attr == 'device_function' and t.decorator_list[0].value.id == 'pyflamegpu':\n self.fill(f\"FLAMEGPU_DEVICE_FUNCTION \")\n if t.returns:\n self.dispatchType(t.returns)\n else:\n self.write(\"void\")\n self.write(f\" {t.name}(\")\n self.dispatchFGPUDeviceFunctionArgs(t)\n self.write(\")\")\n # add to list of defined functions that can be called\n self._device_functions.append(t.name)\n # FLAMEGPU_DEVICE_FUNCTION\n elif t.decorator_list[0].attr == 'agent_function_condition' and t.decorator_list[0].value.id == 'pyflamegpu':\n # check for return annotation\n if not hasattr(t, \"returns\"):\n self.RaiseError(t, \"Agent function conditions must have a 'bool' return type specified as a return type annotation\")\n # check for return annotation type\n if not isinstance(t.returns, ast.Name):\n self.RaiseError(t, \"Agent function conditions return type must be 'bool'\")\n if t.returns.id is not 'bool':\n self.RaiseError(t, \"Agent function conditions return type must be 'bool'\")\n # check to ensure no arguments (discard any with a warning)\n if t.args.args:\n self.RaiseWarning(t, \"Agent function conditions does not support arguments. These will be discarded.\")\n # write the agent function macro\n self.fill(f\"FLAMEGPU_AGENT_FUNCTION_CONDITION({t.name})\")\n else:\n self.RaiseError(t, \"Function definition uses an unsupported decorator. Must use either 'pyflamegpu.agent_function', 'pyflamegpu.agent_function_condition' or 'pyflamegpu.device_function'\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n\n def _AsyncFunctionDef(self, t):\n self.RaiseError(t, \"Async functions not supported\")\n\n def _For(self, t):\n \"\"\"\n Two type for for loop are supported. Either;\n 1) Message for loop in which case the format requires a iterator using the named pyflamegpu function argument of 'message_in'\n 2) A range based for loop with 1 to 3 arguments which is converted into a c style loop\n \"\"\"\n # if message loop then process differently\n if isinstance(t.iter, ast.Name):\n if t.iter.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t, \"Range based for loops only support message iteration using 'message_in' iterator\")\n # do not support for else\n elif t.orelse:\n self.RaiseError(t, \"For else not supported\")\n # allow calls but only to range function\n elif isinstance(t.iter, ast.Call):\n # simple function call e.g. message_in() or range()\n if isinstance(t.iter.func, ast.Name):\n # catch case of message_input with arguments (e.g. spatial messaging)\n if t.iter.func.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n # otherwise permit only range based for loops\n elif t.iter.func.id == \"range\":\n # switch on different uses of range based on number of arguments\n if len(t.iter.args) == 1:\n self.fill(f\"for (int \")\n self.dispatch(t.target)\n self.write(\"=0;\")\n self.dispatch(t.target)\n self.write(\"<\")\n self.dispatch(t.iter.args[0])\n self.write(\";\")\n self.dispatch(t.target)\n self.write(\"++)\")\n elif len(t.iter.args) == 2:\n self.fill(f\"for (int \")\n self.dispatch(t.target)\n self.write(\"=\")\n self.dispatch(t.iter.args[0])\n self.write(\";\")\n self.dispatch(t.target)\n self.write(\"<\")\n self.dispatch(t.iter.args[1])\n self.write(\";\")\n self.dispatch(t.target)\n self.write(\"++)\")\n elif len(t.iter.args) == 3:\n self.fill(f\"for (int \")\n self.dispatch(t.target)\n self.write(\"=\")\n self.dispatch(t.iter.args[0])\n self.write(\";\")\n self.dispatch(t.target)\n self.write(\"<\")\n self.dispatch(t.iter.args[1])\n self.write(\";\")\n self.dispatch(t.target)\n self.write(\"+=\")\n self.dispatch(t.iter.args[2])\n self.write(\")\")\n else:\n self.RaiseError(t, \"Range based for loops requires use of 'range' function with arguments and not keywords\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n else:\n self.RaiseError(t, \"Range based for loops only support calls to the 'range' function\")\n # member function call can only be on message_in.func() type call.\n elif isinstance(t.iter.func, ast.Attribute):\n # must be an attribute (e.g. calling a member of message_in)\n if t.iter.func.value.id == self._input_message_var:\n self.dispatchMessageLoop(t)\n else:\n self.RaiseError(t, \"Range based for loops only support calling members of message input variable\")\n else:\n self.RaiseError(t, \"Range based for loops only support message iteration or use of 'range'\")\n else:\n self.RaiseError(t, \"Range based for loops only support message iteration or use of 'range'\")\n\n def _AsyncFor(self, t):\n self.RaiseError(t, \"Async for not supported\") \n\n def _If(self, t):\n \"\"\"\n Fairly straightforward translation to if, else if, else format\n \"\"\"\n self.fill(\"if (\")\n self.dispatch(t.test)\n self.write(\")\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n # collapse nested ifs into equivalent elifs.\n while (t.orelse and len(t.orelse) == 1 and\n isinstance(t.orelse[0], ast.If)):\n t = t.orelse[0]\n self.fill(\"else if (\")\n self.dispatch(t.test)\n self.write(\")\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n # final else\n if t.orelse:\n self.fill(\"else\")\n self.enter()\n self.dispatch(t.orelse)\n self.leave()\n\n def _While(self, t):\n \"\"\"\n Straightforward translation to c style while loop\n \"\"\"\n self.fill(\"while (\")\n self.dispatch(t.test)\n self.write(\")\")\n self.enter()\n self.dispatch(t.body)\n self.leave()\n if t.orelse:\n self.RaiseError(t, \"While else not supported\")\n\n def _With(self, t):\n self.RaiseError(t, \"With not supported\")\n\n def _AsyncWith(self, t):\n self.RaiseError(t, \"Async with not supported\")\n\n # expr\n def _Bytes(self, t):\n self.RaiseError(t, \"Byte strings and Bytes function not supported\")\n\n def _Str(self, tree):\n # force writing in double quotes\n self.write(f'\"{tree.s}\"')\n \n def _JoinedStr(self, t):\n self.RaiseError(t, \"Joined strings not supported\")\n\n def _FormattedValue(self, t):\n self.RaiseError(t, \"Formatted strings not supported\")\n\n def _fstring_JoinedStr(self, t, write):\n self.RaiseError(t, \"F strings not supported\")\n\n def _fstring_Str(self, t, write):\n self.RaiseError(t, \"F strings not supported\")\n\n def _fstring_Constant(self, t, write):\n self.RaiseError(t, \"F strings not supported\")\n\n def _fstring_FormattedValue(self, t, write):\n self.RaiseError(t, \"F strings not supported\")\n\n def _Name(self, t):\n \"\"\"\n Everything ends up as a Name once it is an identifier\n \"\"\"\n self.write(t.id)\n\n def _NameConstant(self, t):\n # Required only for Python 3.7\n if t.value == None:\n self.write(0)\n elif t.value:\n self.write(\"true\")\n else:\n self.write(\"false\")\n\n def _Repr(self, t):\n self.RaiseError(t, \"Repr not supported\")\n \n def _Constant(self, t):\n \"\"\"\n Restrict most types of constant except for numeric types and constant strings\n Picks up some obvious conversions such as None and Bools\n \"\"\"\n value = t.value\n if isinstance(value, tuple):\n self.RaiseError(t, \"Tuples not supported\")\n if isinstance(value, dict):\n self.RaiseError(t, \"Dictionaries not supported\")\n if isinstance(value, list):\n self.RaiseError(t, \"Lists not supported\")\n elif value is Ellipsis: # instead of `...` for Py2 compatibility\n self.RaiseError(t, \"Ellipsis not supported\")\n elif isinstance(value, str): \n self.write(f'\"{value}\"')\n elif isinstance(value, (bytes, bytearray)): # reject bytes strings e.g. b'123' \n self.RaiseError(t, \"Byte strings and Bytes function not supported\")\n elif isinstance(value, bool):\n if value:\n self.write(\"true\")\n else:\n self.write(\"false\")\n elif value == None:\n self.write(0)\n else:\n self.write(repr(value))\n\n def _Num(self, t):\n self.write(repr(t.n))\n\n def _List(self, t):\n self.RaiseError(t, \"Lists not supported\")\n\n def _ListComp(self, t):\n self.RaiseError(t, \"List comprehension not supported\")\n\n def _GeneratorExp(self, t):\n self.RaiseError(t, \"Generator expressions not supported\")\n\n def _SetComp(self, t):\n self.RaiseError(t, \"Set comprehension not supported\")\n\n def _DictComp(self, t):\n self.RaiseError(t, \"Dictionary comprehension not supported\")\n\n def _comprehension(self, t):\n self.RaiseError(t, \"Comprehension not supported\")\n\n def _IfExp(self, t):\n \"\"\"\n Equivalent to a ternary operator\n \"\"\"\n self.dispatch(t.test)\n self.write(\" ? \")\n self.dispatch(t.body)\n self.write(\" : \")\n self.dispatch(t.orelse)\n\n\n def _Set(self, t):\n self.RaiseError(t, \"Sets not supported\")\n\n def _Dict(self, t):\n self.RaiseError(t, \"Dictionaries not supported\")\n\n def _Tuple(self, t):\n self.RaiseError(t, \"Tuples not supported\")\n\n unop = {\"Invert\":\"~\", \"Not\": \"!\", \"UAdd\":\"+\", \"USub\":\"-\"}\n def _UnaryOp(self, t):\n \"\"\"\n Translate to C equivalent opertaors\n \"\"\"\n self.write(\"(\")\n self.write(self.unop[t.op.__class__.__name__])\n self.dispatch(t.operand)\n self.write(\")\")\n\n binop = { \"Add\":\"+\", \"Sub\":\"-\", \"Mult\":\"*\", \"MatMult\":\"@\", \"Div\":\"/\", \"Mod\":\"%\",\n \"LShift\":\"<<\", \"RShift\":\">>\", \"BitOr\":\"|\", \"BitXor\":\"^\", \"BitAnd\":\"&\",\n \"FloorDiv\":\"//\", \"Pow\": \"**\"}\n def _BinOp(self, t):\n \"\"\"\n Python style pow and floordiv are not supported so translate to a function call.\n No matrix mul support.\n \"\"\"\n op_name = t.op.__class__.__name__\n # translate pow into function call (no float version)\n if op_name == \"Pow\":\n self.write(\"pow(\")\n self.dispatch(t.left)\n self.write(\", \")\n self.dispatch(t.right)\n self.write(\")\")\n # translate floor div into function call (no float version)\n elif op_name == \"FloorDiv\":\n self.write(\"floor(\")\n self.dispatch(t.left)\n self.write(\"/\")\n self.dispatch(t.right)\n self.write(\")\")\n elif op_name == \"MatMult\":\n self.RaiseError(t, \"Matrix multiplier operator not supported\")\n else:\n self.write(\"(\")\n self.dispatch(t.left)\n self.write(\" \" + self.binop[op_name] + \" \")\n self.dispatch(t.right)\n self.write(\")\")\n\n cmpops = {\"Eq\":\"==\", \"NotEq\":\"!=\", \"Lt\":\"<\", \"LtE\":\"<=\", \"Gt\":\">\", \"GtE\":\">=\",\n \"Is\":\"==\", \"IsNot\":\"!=\", \"In\":\"in\", \"NotIn\":\"not in\"}\n def _Compare(self, t):\n self.dispatch(t.left)\n for o, e in zip(t.ops, t.comparators):\n # detect list ops\n if o.__class__.__name__ == \"In\" or o.__class__.__name__ == \"NotIn\":\n self.RaiseError(t, \"In and NotIn operators not supported\")\n self.write(\" \" + self.cmpops[o.__class__.__name__] + \" \")\n self.dispatch(e)\n\n boolops = {ast.And: '&&', ast.Or: '||'}\n def _BoolOp(self, t):\n \"\"\"\n Translate to logical and/or operators in C\n \"\"\"\n self.write(\"(\")\n s = \" %s \" % self.boolops[t.op.__class__]\n interleave(lambda: self.write(s), self.dispatch, t.values)\n self.write(\")\")\n \n def _Attribute(self,t):\n \"\"\"\n A very limited set of attributes are supported so these are fully evaluated here. Other places where attribute type expressions may occur will also evaluate them fully rather than recursively call this function.\n Attributes supported are only;\n * pyflamegpu.attribute - a supported attribute e.g. pyflamegpu.ALIVE. This will be translated into a namespace member.\n * math.constant - Any supported math constants are translated to C definition versions\n \"\"\"\n # Only a limited set of globals supported\n func_dict = None\n \n # pyflamegpu singleton\n if isinstance(t.value, ast.Name):\n if t.value.id == \"pyflamegpu\":\n if t.attr in self.fgpu_attrs:\n # proceed\n self.write(\"flamegpu::\")\n self.write(t.attr)\n else:\n self.RaiseError(t, f\"Attribute '{t.attr}' does not exist in pyflamegpu object\")\n # math functions (try them in raw function call format) or constants\n elif t.value.id == \"math\":\n if t.attr in self.mathconsts:\n self.write(self.mathconsts[t.attr])\n else:\n self.RaiseError(t, f\"Unsupported math constant '{t.attr}'\")\n # numpy types\n elif t.value.id == \"numpy\" or t.value.id == \"np\":\n # not sure how a numpy attribute would be used without function call or type hint but translate anyway \n if t.attr in self.numpytypes:\n self.write(self.numpytypes[t.attr])\n else: \n self.RaiseError(t, f\"Unsupported numpy type {t.attr}\")\n else:\n self.RaiseError(t, f\"Global '{t.value.id}' identifiers not supported\")\n else:\n self.RaiseError(t, \"Unsupported attribute\")\n\n def _CallArguments(self, t):\n comma = False\n for e in t.args:\n if comma: self.write(\", \")\n else: comma = True\n self.dispatch(e)\n if len(t.keywords):\n self.RaiseWarning(t, \"Keyword argument not supported. Ignored.\")\n if sys.version_info[:2] < (3, 5):\n if t.starargs:\n self.RaiseWarning(t, \"Starargs not supported. Ignored.\")\n if t.kwargs:\n self.RaiseWarning(t, \"Kwargs not supported. Ignored.\")\n \n def _Call(self, t):\n \"\"\"\n Some basic checks are undertaken on calls to ensure that the function being called is either a builtin or defined device function.\n A special dispatcher is required \n \"\"\"\n # check calls but let attributes check in their own dispatcher\n funcs = self._device_functions + self.pythonbuiltins + [self._input_message_var] # message_input variable is a valid function name as certain message types have arguments on iterator\n if isinstance(t.func, ast.Name):\n if (t.func.id not in funcs):\n self.RaiseWarning(t, \"Function call is not a defined FLAME GPU device function or a supported python built in.\")\n # dispatch even if warning raised\n self.dispatch(t.func)\n elif isinstance(t.func, ast.Lambda):\n self.dispatch(t.func) # not supported\n else:\n # special handler for dispatching member function calls\n # This would otherwise be an attribute\n self.dispatchMemberFunction(t.func, t) \n self.write(\"(\")\n self._CallArguments(t)\n self.write(\")\")\n\n def _Subscript(self, t):\n \"\"\"\n Arrays are not supported but subscript allows accessing array like variables which is required for macro environment properties (e.g. a[0][1][2])\n Obvious limitation is no slicing type syntax (e.g. a[:2])\n \"\"\"\n self.dispatch(t.value)\n self.write(\"[\")\n self.dispatch(t.slice)\n self.write(\"]\")\n\n def _Starred(self, t):\n self.RaiseError(t, \"Starred values not supported\")\n\n # slice\n def _Ellipsis(self, t):\n self.RaiseError(t, \"Ellipsis values not supported\")\n\n def _Index(self, t):\n self.RaiseError(t, \"Index values not supported\")\n\n def _Slice(self, t):\n self.RaiseError(t, \"Slicing values not supported\")\n\n def _ExtSlice(self, t):\n self.RaiseError(t, \"ExtSlice values not supported\")\n\n # argument\n def _arg(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, \"Arguments should already have been processed\")\n\n # others\n def _arguments(self, t):\n \"\"\"\n Arguments should be processed by a custom dispatcher and it should not be possible to get here\n \"\"\"\n self.RaiseError(t, \"Arguments should already have been processed\")\n\n def _keyword(self, t):\n self.RaiseError(t, \"Keywords are not supported\")\n\n def _Lambda(self, t):\n self.RaiseError(t, \"Lambda is not supported\")\n\n def _alias(self, t):\n self.RaiseError(t, \"Aliasing is not supported\")\n\n def _withitem(self, t):\n self.RaiseError(t, \"With not supported\")\n",
"step-ids": [
43,
45,
82,
94,
103
]
}
|
[
43,
45,
82,
94,
103
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 09:54:28 2020
@author: rushirajsinhparmar
"""
import matplotlib.pyplot as plt
from skimage import io
import numpy as np
from skimage.filters import threshold_otsu
import cv2
img = io.imread("texture.png", as_gray=True)
##################################################
#Variance - not a great way to quantify texture
from scipy import ndimage
k=7
img_mean = ndimage.uniform_filter(img, (k, k))
img_sqr_mean = ndimage.uniform_filter(img**2, (k, k))
img_var = img_sqr_mean - img_mean**2
plt.imshow(img_var, cmap='gray')
#######################################################
#GABOR - A great filter for texture but usually efficient
#if we know exact parameters. Good choice for generating features
#for machine learning
ksize=45
theta=np.pi/2
kernel = cv2.getGaborKernel((ksize, ksize), 5.0, theta, 10.0, 0.9, 0, ktype=cv2.CV_32F)
filtered_image = cv2.filter2D(img, cv2.CV_8UC3, kernel)
plt.imshow(filtered_image, cmap='gray')
###########################################################
#Entropy
#Entropy quantifies disorder.
#Since cell region has high variation in pixel values the entropy would be
#higher compared to scratch region
from skimage.filters.rank import entropy
from skimage.morphology import disk
entropy_img = entropy(img, disk(15))
plt.imshow(entropy_img)
#use otsu to threshold high vs low entropy regions.
plt.hist(entropy_img.flat, bins=100, range=(0,7)) #.flat returns the flattened numpy array (1D)
thresh = threshold_otsu(entropy_img)
#binarize the entropy image
binary = entropy_img <= thresh
plt.imshow(binary)
#Sum all pixels in the scratch region (values =1)
scratch_area = np.sum(binary == 1)
print("Scratched area is: ", scratch_area, "Square pixels")
scale = 0.45 # microns/pixel
print("Scratched area in sq. microns is: ", scratch_area*((scale)**2), "Square pixels")
|
normal
|
{
"blob_id": "ab6c3d3c6faa2d1fe5e064dbdebd8904b9434f15",
"index": 5214,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.imshow(img_var, cmap='gray')\n<mask token>\nplt.imshow(filtered_image, cmap='gray')\n<mask token>\nplt.imshow(entropy_img)\nplt.hist(entropy_img.flat, bins=100, range=(0, 7))\n<mask token>\nplt.imshow(binary)\n<mask token>\nprint('Scratched area is: ', scratch_area, 'Square pixels')\n<mask token>\nprint('Scratched area in sq. microns is: ', scratch_area * scale ** 2,\n 'Square pixels')\n",
"step-3": "<mask token>\nimg = io.imread('texture.png', as_gray=True)\n<mask token>\nk = 7\nimg_mean = ndimage.uniform_filter(img, (k, k))\nimg_sqr_mean = ndimage.uniform_filter(img ** 2, (k, k))\nimg_var = img_sqr_mean - img_mean ** 2\nplt.imshow(img_var, cmap='gray')\nksize = 45\ntheta = np.pi / 2\nkernel = cv2.getGaborKernel((ksize, ksize), 5.0, theta, 10.0, 0.9, 0, ktype\n =cv2.CV_32F)\nfiltered_image = cv2.filter2D(img, cv2.CV_8UC3, kernel)\nplt.imshow(filtered_image, cmap='gray')\n<mask token>\nentropy_img = entropy(img, disk(15))\nplt.imshow(entropy_img)\nplt.hist(entropy_img.flat, bins=100, range=(0, 7))\nthresh = threshold_otsu(entropy_img)\nbinary = entropy_img <= thresh\nplt.imshow(binary)\nscratch_area = np.sum(binary == 1)\nprint('Scratched area is: ', scratch_area, 'Square pixels')\nscale = 0.45\nprint('Scratched area in sq. microns is: ', scratch_area * scale ** 2,\n 'Square pixels')\n",
"step-4": "<mask token>\nimport matplotlib.pyplot as plt\nfrom skimage import io\nimport numpy as np\nfrom skimage.filters import threshold_otsu\nimport cv2\nimg = io.imread('texture.png', as_gray=True)\nfrom scipy import ndimage\nk = 7\nimg_mean = ndimage.uniform_filter(img, (k, k))\nimg_sqr_mean = ndimage.uniform_filter(img ** 2, (k, k))\nimg_var = img_sqr_mean - img_mean ** 2\nplt.imshow(img_var, cmap='gray')\nksize = 45\ntheta = np.pi / 2\nkernel = cv2.getGaborKernel((ksize, ksize), 5.0, theta, 10.0, 0.9, 0, ktype\n =cv2.CV_32F)\nfiltered_image = cv2.filter2D(img, cv2.CV_8UC3, kernel)\nplt.imshow(filtered_image, cmap='gray')\nfrom skimage.filters.rank import entropy\nfrom skimage.morphology import disk\nentropy_img = entropy(img, disk(15))\nplt.imshow(entropy_img)\nplt.hist(entropy_img.flat, bins=100, range=(0, 7))\nthresh = threshold_otsu(entropy_img)\nbinary = entropy_img <= thresh\nplt.imshow(binary)\nscratch_area = np.sum(binary == 1)\nprint('Scratched area is: ', scratch_area, 'Square pixels')\nscale = 0.45\nprint('Scratched area in sq. microns is: ', scratch_area * scale ** 2,\n 'Square pixels')\n",
"step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 14 09:54:28 2020\n\n@author: rushirajsinhparmar\n\"\"\"\n\nimport matplotlib.pyplot as plt\nfrom skimage import io\n\nimport numpy as np\nfrom skimage.filters import threshold_otsu\nimport cv2\n\nimg = io.imread(\"texture.png\", as_gray=True)\n\n##################################################\n#Variance - not a great way to quantify texture\nfrom scipy import ndimage \nk=7\nimg_mean = ndimage.uniform_filter(img, (k, k))\nimg_sqr_mean = ndimage.uniform_filter(img**2, (k, k))\nimg_var = img_sqr_mean - img_mean**2\nplt.imshow(img_var, cmap='gray')\n\n#######################################################\n#GABOR - A great filter for texture but usually efficient\n#if we know exact parameters. Good choice for generating features\n#for machine learning\n\nksize=45\ntheta=np.pi/2\nkernel = cv2.getGaborKernel((ksize, ksize), 5.0, theta, 10.0, 0.9, 0, ktype=cv2.CV_32F)\nfiltered_image = cv2.filter2D(img, cv2.CV_8UC3, kernel)\nplt.imshow(filtered_image, cmap='gray')\n\n###########################################################\n#Entropy\n#Entropy quantifies disorder.\n#Since cell region has high variation in pixel values the entropy would be\n#higher compared to scratch region\nfrom skimage.filters.rank import entropy\nfrom skimage.morphology import disk\nentropy_img = entropy(img, disk(15))\nplt.imshow(entropy_img) \n\n#use otsu to threshold high vs low entropy regions.\nplt.hist(entropy_img.flat, bins=100, range=(0,7)) #.flat returns the flattened numpy array (1D)\n\nthresh = threshold_otsu(entropy_img) \n\n#binarize the entropy image \nbinary = entropy_img <= thresh\nplt.imshow(binary)\n\n#Sum all pixels in the scratch region (values =1)\nscratch_area = np.sum(binary == 1)\nprint(\"Scratched area is: \", scratch_area, \"Square pixels\")\n\nscale = 0.45 # microns/pixel\nprint(\"Scratched area in sq. microns is: \", scratch_area*((scale)**2), \"Square pixels\")",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.